<!DOCTYPE html>
<html prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article# " lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SQLAlchemy Introduce | 绿萝间</title>
<link href="../assets/css/all-nocdn.css" rel="stylesheet" type="text/css">
<link href="../assets/css/ipython.min.css" rel="stylesheet" type="text/css">
<link href="../assets/css/nikola_ipython.css" rel="stylesheet" type="text/css">
<meta name="theme-color" content="#5670d4">
<meta name="generator" content="Nikola (getnikola.com)">
<link rel="alternate" type="application/rss+xml" title="RSS" href="../rss.xml">
<link rel="canonical" href="https://muxuezi.github.io/posts/sqlalchemy-introduce.html">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        processEscapes: true
    },
    displayAlign: 'center', // Change this to 'center' to center equations.
    "HTML-CSS": {
        styles: {'.MathJax_Display': {"margin": 0}}
    }
});
</script><!--[if lt IE 9]><script src="../assets/js/html5.js"></script><![endif]--><meta name="author" content="Tao Junjie">
<link rel="prev" href="postgres-import-csv-cp936-error.html" title="Postgres Import CSV cp936 Error" type="text/html">
<link rel="next" href="slott-2015146-2015-12-13-report.html" title="双色球2015146期(2015-12-13)数据分析报告" type="text/html">
<meta property="og:site_name" content="绿萝间">
<meta property="og:title" content="SQLAlchemy Introduce">
<meta property="og:url" content="https://muxuezi.github.io/posts/sqlalchemy-introduce.html">
<meta property="og:description" content="perface¶








我们每天都要面对数据，数据库CRUD操作的能力对每个任务都至关重要。无论你是开发网页，桌面或其他应用，他们都需要快速且安全的接入数据。关系型数据库仍然是储存数据最主流的手段之一。
SQL是操作数据的利器，不过有时候要整合到应用里非常麻烦。作为一个Pythoner，你可能需要通过ODBC接口或者数据库API，用一些字符串生成查询。虽然这些方法可以有效的处理数据，但是">
<meta property="og:type" content="article">
<meta property="article:published_time" content="2015-12-13T19:17:02+08:00">
<meta property="article:tag" content="ipython">
<meta property="article:tag" content="sql">
</head>
<body>
<a href="#content" class="sr-only sr-only-focusable">Skip to main content</a>

<!-- Menubar -->

<nav class="navbar navbar-inverse navbar-static-top"><div class="container">
<!-- This keeps the margins nice -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar" aria-controls="bs-navbar" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="https://muxuezi.github.io/">

                <span id="blog-title">绿萝间</span>
            </a>
        </div>
<!-- /.navbar-header -->
        <div class="collapse navbar-collapse" id="bs-navbar" aria-expanded="false">
            <ul class="nav navbar-nav">
<li>
<a href="../archive.html">Archive</a>
                </li>
<li>
<a href="../categories/">Tags</a>
                </li>
<li>
<a href="../rss.xml">RSS feed</a>

                
            </li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
    <a href="sqlalchemy-introduce.ipynb" id="sourcelink">Source</a>
    </li>

                
            </ul>
</div>
<!-- /.navbar-collapse -->
    </div>
<!-- /.container -->
</nav><!-- End of Menubar --><div class="container" id="content" role="main">
    <div class="body-content">
        <!--Body content-->
        <div class="row">
            
            
<article class="post-text h-entry hentry postpage" itemscope="itemscope" itemtype="http://schema.org/Article"><header><h1 class="p-name entry-title" itemprop="headline name"><a href="#" class="u-url">SQLAlchemy Introduce</a></h1>

        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                    Tao Junjie
            </span></p>
            <p class="dateline"><a href="#" rel="bookmark"><time class="published dt-published" datetime="2015-12-13T19:17:02+08:00" itemprop="datePublished" title="2015-12-13 19:17">2015-12-13 19:17</time></a></p>
            
        <p class="sourceline"><a href="sqlalchemy-introduce.ipynb" id="sourcelink">Source</a></p>

        </div>
        

    </header><div class="e-content entry-content" itemprop="articleBody text">
    <div tabindex="-1" id="notebook" class="border-box-sizing">
    <div class="container" id="notebook-container">

<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="perface">perface<a class="anchor-link" href="sqlalchemy-introduce.html#perface">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>我们每天都要面对数据，数据库CRUD操作的能力对每个任务都至关重要。无论你是开发网页，桌面或其他应用，他们都需要快速且安全的接入数据。关系型数据库仍然是储存数据最主流的手段之一。</p>
<p>SQL是操作数据的利器，不过有时候要整合到应用里非常麻烦。作为一个Pythoner，你可能需要通过ODBC接口或者数据库API，用一些字符串生成查询。虽然这些方法可以有效的处理数据，但是数据安全和修改变得很困难。</p>
<p>这本书将介绍一个非常强大且具有灵活性的Python库SQLAlchemy，可以跨越关系型数据库与传统编程直接的鸿沟。SQLAlchemy允许你使用原始的SQL语言查询，更鼓励使用更高级的Pythonic展示方式和更友好的方法实现数据的查询和更新。它提供工具让你一次性把应用的类和对象映射成数据库的表，然后就可以不再理会表结构了，还可以让你不断优化模型的性能。</p>
<p>SQLAlchemy功能强大且充满柔性，但它还是有点复杂。SQLAlchemy教程只介绍了它的冰山一角，尽管在线文档也很全，但是更适合做参考书，不适合做教程。这本书的目的是要成为一个学习工具和一个方便的参考，帮你快速完成任务。</p>
<p>本书内容用的SQLAlchemy是1.0版本；但是之前的版本都可以用。0.8版可能需要一点小改动，大部分都是源自0.5版。</p>
<p>这本书分成三部分：SQLAlchemy Core，SQLAlchemy ORM和一个Cookbook部分。前两部分尽可能的做到一致性。我们有意在两个部分用同意的例子，目的是让你更方便的比较两种方式的用法。因此，你也可以根据自己的需要阅读本书SQLAlchemy Core和SQLAlchemy ORM的章节。</p>
<!-- TEASER_END-->
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="1.SQLAlchemy简介">1.SQLAlchemy简介<a class="anchor-link" href="sqlalchemy-introduce.html#1.SQLAlchemy%E7%AE%80%E4%BB%8B">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>SQLAlchemy是一个与数据库进行交互的库。它可以让你用Python的类和语句创建数据模型来查询数据。在2005年由Mike Bayer创建，SQLAlchemy被许多公司使用，已经渐渐成为Python处理关系型数据库的一种主流手段。</p>
<p>它可以连接许多数据库，包括 Postgres，MySQL，SQLite和Oracle等等。也提供了一种通用的接口支持其他关系型数据库。Amazon的Redshift数据库，作为Postgres的一种变体，就是SQLAlchemy社区对数据库支持的好榜样。</p>
<p>本章，我们将首先解释为什么要用SQLAlchemy，然后介绍两个主要模型并连接一个数据库。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="为什么用SQLAlchemy">为什么用SQLAlchemy<a class="anchor-link" href="sqlalchemy-introduce.html#%E4%B8%BA%E4%BB%80%E4%B9%88%E7%94%A8SQLAlchemy">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>用SQLAlchemy的主要原因是，把你从底层的数据库和SQL奇葩语法中解放出来。SQLAlchemy将常用语句和类型和SQL语句对应起来，让你可以更容易地理解数据库类型，而不需要担心太多细节。这样在处理像Oracle到PostgreSQL数据库这类的迁移工作，或从一个应用数据库到数据仓库时，事情就简单了。它还能确保数据在增加到数据库之前是经过安全的，适当转义处理的。这样可以避免SQL注入之类的事情发生。</p>
<p>SQLAlchemy通过两个主要的模型来实现灵活的操作：SQL表达式语言（通常也叫Core）和ORM（Object-relational mapping，对象关系映射）。这两个模型可以根据你的需要独立使用，也可以合在一起使用。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="SQLAlchemy-Core和SQL表达式语言">SQLAlchemy Core和SQL表达式语言<a class="anchor-link" href="sqlalchemy-introduce.html#SQLAlchemy-Core%E5%92%8CSQL%E8%A1%A8%E8%BE%BE%E5%BC%8F%E8%AF%AD%E8%A8%80">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>SQL表达式语言是用Pythonic方式的来表达SQL语句和表达式，只是对传统的SQL语言的轻微抽象。它侧重于实用数据库的模式（schema，其实是具体到一个Tabel和View等），但是它实现了不同数据库之间标准化的接口。SQL表达式语言也是SQLAlchemy ORM的基础。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="ORM">ORM<a class="anchor-link" href="sqlalchemy-introduce.html#ORM">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>SQLAlchemy ORM与你在其他语言里遇到的ORM类似。它侧重于应用的Domain Model（一种将数据与其行为集成在一起的模式），借助工作单元的模式来维护对象状态。它还在SQL表达式语言之上增加了一层抽象，让用户可以更容易的操作数据库。你可以把ORM和SQL表达式语言结合起来构建强大的应用。ORM构建了一个声明式的系统，与许多其他ORM模型（如Ruby on Rails）使用的 active-record systems类似。</p>
<p>虽然ORM非常有用，但是你要注意，类的很多用法与数据库的工作方式是不一样的。我们将在后面的章节介绍这些差异。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="Core和ORM的选择">Core和ORM的选择<a class="anchor-link" href="sqlalchemy-introduce.html#Core%E5%92%8CORM%E7%9A%84%E9%80%89%E6%8B%A9">¶</a>
</h3>
<p>究竟是选择Core还是ORM作为应用的数据链接层呢？除了个人喜好，理由可以归结为一些影响因素。这两种模式的语法不太一样，但Core和ORM最大的差异是Core对数据模式和<a href="https://en.wikipedia.org/wiki/Business_object">业务对象（business objects）</a>的不同处理方式。</p>
<p>SQLAlchemy Core是以模式为中心，和普通SQL一样有表，键和索引等。SQLAlchemy Core最擅长的时数据仓库，报表分析，以及其他使用数据查询和其他操作可以牢牢掌控的地方。它拥有强大的数据库连接池（ connection pool）和数据结果集（ResultSet）优化，非常适合处理大量数据，甚至多数据库也适用。</p>
<p>但是，如果你更侧重于<a href="https://en.wikipedia.org/wiki/Domain-driven_design">领域驱动设计(domain driven design)</a>，那么ORM就可以将原数据和业务对象的底层的模式和结构大部分细节都封装起来。这样封装让数据库连接更简单，更像Python代码。大多数应用都更适合按照这种方法建模。ORM可以用一种非常高效的方法把领域驱动设计方法导入传统应用，或者改造原来带有原始SQL语句的应用。还有一个好处就是，通过对底层数据库的合理抽象，ORM让开发者把精力更多地集中在业务流程的实现上。</p>
<p>不过，ORM是建立在SQLAlchemy Core基础之上的，你可以把处理MySQL的同样方式用于Oracle的数据仓库和Amazon Redshift数据库。当你需要业务对象和仓库数据时，ORM可以无缝的衔接每个环节。</p>
<ul>
<li>如果你的应用框架已经使用了ORM，但是想要更强大的报表功能，使用Core</li>
<li>如果你不想像普通SQL一样以模式为中心，用ORM</li>
<li>如果你的数据不需要业务对象，用Core</li>
<li>如果你把数据看成业务对象，用ORM</li>
<li>如果要建立快速原型，用ORM</li>
<li>如果你既要业务对象，又要其他数据无关的功能（报表，数据分析等等），两个都用。</li>
</ul>
<p>知道了如何选择Core和ORM，我们介绍SQLAlchemy的安装与数据库连接方法。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="SQLAlchemy安装与数据库连接">SQLAlchemy安装与数据库连接<a class="anchor-link" href="sqlalchemy-introduce.html#SQLAlchemy%E5%AE%89%E8%A3%85%E4%B8%8E%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5">¶</a>
</h3>
<p>SQLAlchemy支持Python 2.6+，Python 3.3+和Pypy 2.1+，强烈推荐conda安装，pip也可以（Python 2.7.5+和Python 3.4+自带pip）。</p>
<div class="highlight"><pre><span></span>conda install sqlalchemy

or 

pip install sqlalchemy
</pre></div>
<h4 id="安装数据库驱动">安装数据库驱动<a class="anchor-link" href="sqlalchemy-introduce.html#%E5%AE%89%E8%A3%85%E6%95%B0%E6%8D%AE%E5%BA%93%E9%A9%B1%E5%8A%A8">¶</a>
</h4>
<p>SQLAlchemy默认支持SQLite3，不需要安装驱动；但是，其他数据库都需要用符合Python的DBAPI（PEP-249）标准的驱动。这些DBAPI提供了与各种数据库进行交互的方言，可以体现不同数据库独有的特性。不同的数据库也可能有多个不同的DBAPI，下面主要介绍PostgreSQL和MySQL数据库的驱动。</p>
<h5 id="PostgreSQL">PostgreSQL<a class="anchor-link" href="sqlalchemy-introduce.html#PostgreSQL">¶</a>
</h5>
<p><a href="http://initd.org/psycopg/">Psycopg2</a>提供了PostgreSQL的驱动，可以用<code>pip install psycopg2</code>安装。</p>
<h5 id="MySQL">MySQL<a class="anchor-link" href="sqlalchemy-introduce.html#MySQL">¶</a>
</h5>
<p><a href="https://github.com/PyMySQL/PyMySQL">PyMySQL</a>是MySQL的驱动，可以用<code>pip install pymysql</code>安装。SQLAlchemy支持MySQL 4.1+版本，由于之前的版本密码工作方式不同。如果某个类型只存在于MySQL的特定版本中，那么SQLAlchemy不会支持那些没有该类型的MySQL版本使用该类型。用MySQL时，如果SQLAlchemy的某个函数不能正常运行，建议看看MySQL的文档。</p>
<h4 id="Others">Others<a class="anchor-link" href="sqlalchemy-introduce.html#Others">¶</a>
</h4>
<p>关于其他数据库的SQLAlchemy支持，请参考SQLAlchemy文档。Drizzle，Firebird，Oracle， Sybase，Microsoft SQL Server都支持。IBM DB2，Informix，Amazon Redshift，EXASolution，SAP SQL Anywhere，Monet等数据库也有SQLAlchemy社区支持。额外的方言也可以由SQLAlchemy支持，在第八章：自定义方言里面有介绍。</p>
<p>有了DBAPI连接件，我们再看看如何连接数据库。</p>
<h4 id="连接数据库">连接数据库<a class="anchor-link" href="sqlalchemy-introduce.html#%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93">¶</a>
</h4>
<p>连接数据库需要SQLAlchemy引擎，SQLAlchemy引擎为数据库执行SQL语句创建了一个常用的接口。引擎通过封装一个数据库连接池和方言来实现不同数据库类型统一的接口。这样做使得Python代码不需要关心不同数据库DBAPI之间的差异。SQLAlchemy提供了一个带连接字符串（connection string）和一些参数的函数来创建引擎。连接字符串形式如下：</p>
<ul>
<li>数据库类型（SQLite，Postgres，MySQL等）</li>
<li>默认数据库类型的方言（Psycopg2，PyMySQL等）</li>
<li>验证信息（用户名和密码）</li>
<li>数据库的位置（文件名或数据库服务器地址）</li>
<li>数据库服务器端口（可选）</li>
<li>数据库名称（可选）</li>
</ul>
<p>SQLite数据库连接字符串就是一个文件或储存位置。例1-1中，第二行表示SQLAlchemy连接了当前文件夹中的一个SQLite数据库文件<code>cookies.db</code>，第三行是连接内存数据库，第四、五行分别是Unix和Windows系统中的全路径文件。Windows系统路径名称分隔符（<code>\</code>）在Python中是<code>'\\'</code>或<code>r'\'</code>。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [1]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">create_engine</span>
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s1">'sqlite:///cookies.db'</span><span class="p">)</span>
<span class="n">engine2</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s1">'sqlite:///:memory:'</span><span class="p">)</span>
<span class="n">engine3</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s1">'sqlite:////home/cookiemonster/cookies.db'</span><span class="p">)</span>
<span class="n">engine3</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s1">'sqlite:///c:</span><span class="se">\\</span><span class="s1">Users</span><span class="se">\\</span><span class="s1">cookiemonster</span><span class="se">\\</span><span class="s1">cookies.db'</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<blockquote>
<p><code>create_engine</code>函数创建了一个引擎实例，但是，它并没有真正打开链接，直到一个动作要求引擎执行时才会执行，比如查询或新建数据。</p>
</blockquote>
<p>下面再让我们创建一个PostgreSQL数据库<code>mydb</code>。然后我们用函数构建一个引擎实例，如例1-2所示，你会发现我用了<code>postgresql+psycopg2</code>作为连接字符串的引擎和方言部分。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [5]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">create_engine</span>
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s1">'postgresql+psycopg2://username:password@localhost:5432/mydb'</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>同理，我们再看看MySQL引擎的创建，如例1-3所示，我们把参数<code>pool_recycle</code>设置成<code>3600</code>，表示每一小时自动连接一次。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">create_engine</span>
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s1">'mysql+pymysql://cookiemonster:chocolatechip'</span>
                       <span class="s1">'@mysql01.monster.internal/cookies'</span><span class="p">,</span> <span class="n">pool_recycle</span><span class="o">=</span><span class="mi">3600</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<blockquote>
<p>MySQL默认超过8小时空闲则断开连接。为了绕开这个问题，引擎设置<code>pool_recycle=3600</code>。</p>
</blockquote>
<p><code>create_engine</code>函数的可选参数是：</p>
<ul>
<li>
<code>echo</code>：表示引擎行为的日志是否显示，像执行的SQL语句和其他参数等等。默认是<code>False</code>。</li>
<li>
<code>ecoding</code>：默认使用SQLAlchemy的字符串编码<code>utf-8</code>，大多数DBAPI都用此编码。</li>
<li>
<code>isolation_level</code>：SQLAlchemy分离等级。PostgreSQL+psycopg2的分类等级有<code>READ COMMITTED</code>，<code>READ UNCOMMITTED</code>，<code>REPEATABLE READ</code>，<code>SERIALIZABLE</code>，<code>AUTOCOMMIT</code>五种，默认是<code>READ COMMITTED</code>。PyMySQL也是这五种，InnoDB存储引擎数据库默认是<code>REPEATABLE READ</code>。<blockquote>
<p>用<code>isolation_level</code>关键词会为具体的DBAPI设置隔离等级，可就像数据库对应连接字符串的键值对一样，比如PostgreSQL是用psycopg2。</p>
</blockquote>
</li>
<li>
<code>pool_recycle</code>：这个参数是指数据库连接多少秒循环检查一次，对MySQL非常重要。默认值为<code>-1</code>，表示没有时间限制，一直连接。</li>
</ul>
<p>一旦引擎建立，我们就可以连接数据库了。通过<code>connect()</code>函数就可以。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">connection</span> <span class="o">=</span> <span class="n">engine</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在我们已经连接了数据库，可以用SQLAlchemy Core和ORM了。下面这部分，我们将探索SQLAlchemy Core的内容，学习如何定义和查询数据库。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="SQLAlchemy-Core">SQLAlchemy Core<a class="anchor-link" href="sqlalchemy-introduce.html#SQLAlchemy-Core">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>连接数据库之后，我们就可以使用SQLAlchemy Core来进行数据库操作了。SQLAlchemy Core是用Pythonic方式的SQL表达式语言来表示SQL命令和数据结构的。SQLAlchemy Core具有的这种特性让它不仅可以用于Django或SQLAlchemy ORM，也可以单独使用。</p>
<p>首先我们需要定义数据表的数据类型，数据的关联性以及其他约束条件。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="2.Schema-and-Types">2.Schema and Types<a class="anchor-link" href="sqlalchemy-introduce.html#2.Schema-and-Types">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>为了搞定数据库，SQLAlchemy提供了以下三种方式来表示数据库中的表结构：</p>
<ul>
<li>
<a href="http://docs.sqlalchemy.org/en/rel_1_0/core/index.html">Core</a>：自定义表<code>Table</code>对象</li>
<li>
<a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/index.html">ORM</a>：用类<code>class</code>表示数据表</li>
<li>
<a href="https://sqlsoup.readthedocs.org/en/latest/">SQLsoup</a>和<a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/extensions/automap.html">Automap</a>：直接从数据库映射</li>
</ul>
<p>本章重点介绍第一种方式，即通过SQLAlchemy Core来实现，后面的章节会介绍其他两种方法。<code>Table</code>对象包括了一系列具有特定类型的列和属性，这些通过一个常用的元数据容器来控制。首先我们介绍SQLAlchemy建数据表的数据类型。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="Types">Types<a class="anchor-link" href="sqlalchemy-introduce.html#Types">¶</a>
</h3>
<p>SQLAlchemy有四种数据类型：</p>
<ul>
<li>通用类型（Generic）</li>
<li>SQL标准类型（SQL standard）</li>
<li>数据库特有类型（Vendor Specific）</li>
<li>用户自定义类型（User Defined）</li>
</ul>
<p>SQLAlchemy为不同的数据库定义了一些通用的数据类型。这些类型都在<code>sqlalchemy.types</code>模块中，为了引用方便也支持放在<code>sqlalchemy</code>里面。</p>
<p>布尔型通用类型使用<code>BOOLEAN</code>SQL类型，对应的Python类型就是<code>True</code>和<code>False</code>；但是，对那些不支持<code>BOOLEAN</code>SQL类型的数据库通常要使用<code>SMALLINT</code>来代替。由于SQLAlchemy把这些细节都隐藏了，因此你可以放心大胆的操作数据，不用担心后面数据库用的是什么细节，只要在Python代码里处理<code>True</code>和<code>False</code>就行。即使数据仓库和交换数据库不一样，通用类型也可以完成数据处理。通用类型对应Python和SQL的含义如下表所示：</p>
<table>
<thead><tr>
<th style="text-align:center">SQLAlchemy</th>
<th style="text-align:center">Python</th>
<th style="text-align:center">SQL</th>
</tr></thead>
<tbody>
<tr>
<td style="text-align:center">BigInteger</td>
<td style="text-align:center">int</td>
<td style="text-align:center">BIGINT</td>
</tr>
<tr>
<td style="text-align:center">Boolean</td>
<td style="text-align:center">bool</td>
<td style="text-align:center">BOOLEAN or SMALLINT</td>
</tr>
<tr>
<td style="text-align:center">Date</td>
<td style="text-align:center">datetime.date</td>
<td style="text-align:center">Date (SQLite: String)</td>
</tr>
<tr>
<td style="text-align:center">DateTime</td>
<td style="text-align:center">datetime.datetime</td>
<td style="text-align:center">DATETIME (SQLite: String)</td>
</tr>
<tr>
<td style="text-align:center">Enum</td>
<td style="text-align:center">str</td>
<td style="text-align:center">ENUM or VARCHAR</td>
</tr>
<tr>
<td style="text-align:center">Float</td>
<td style="text-align:center">float or Decimal</td>
<td style="text-align:center">FLOAT or REAL</td>
</tr>
<tr>
<td style="text-align:center">Integer</td>
<td style="text-align:center">int</td>
<td style="text-align:center">Integer</td>
</tr>
<tr>
<td style="text-align:center">Interval</td>
<td style="text-align:center">datetime.timedelta</td>
<td style="text-align:center">INTERVAL or DATE from epoch</td>
</tr>
<tr>
<td style="text-align:center">LargeBinary</td>
<td style="text-align:center">byte</td>
<td style="text-align:center">BLOB or BYTEA</td>
</tr>
<tr>
<td style="text-align:center">Numeric</td>
<td style="text-align:center">decimal.Decimal</td>
<td style="text-align:center">NUMERIC or DECIMAL</td>
</tr>
<tr>
<td style="text-align:center">Unicode</td>
<td style="text-align:center">unicode</td>
<td style="text-align:center">UNICODE or VARCHAR</td>
</tr>
<tr>
<td style="text-align:center">Text</td>
<td style="text-align:center">str</td>
<td style="text-align:center">CLOB or TEXT</td>
</tr>
<tr>
<td style="text-align:center">Time</td>
<td style="text-align:center">datetime.time</td>
<td style="text-align:center">DATETIME</td>
</tr>
</tbody>
</table>
<blockquote>
<p>掌握通用类型非常重要，会经常使用</p>
</blockquote>
<p>如果通用类型不能满足需求，也会用到SQL标准类型和数据库专有类型。<code>CHAR</code>和<code>NVARCHAR</code>类型就是最好的例证，源自SQL类型。如果数据库的模式是在使用SQLAlchemy之前建立的，我们就要注意原模式与SQLAlchemy的差异。SQL标准类型的特性在不同的数据库里面可能有很大变化，也是在<code>sqlalchemy.types</code>模块中，为了和通用类型分开，都用大写字母表示。</p>
<p>数据库专有类型只存在于特定的数据库中。你可以通过SQLALchemy网站或某种数据库的方言（dialect）文档查询此类型，放在<code>sqlalchemy.dialects</code>模块和数据库方言的子模块中，这些类型同样是大写字母。例如，我们想使用PostgreSQL强大的JSON类型，我们可以这样：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy.dialects.postgresql</span> <span class="k">import</span> <span class="n">JSON</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这样我们就可以用PostgreSQL特有的JSON函数为我们的应用定义JSON类型，比如<code>array_to_json</code>。</p>
<p>你也可以根据自己的需要自定义类型。例如，当增加数据记录时，需要对即将存储到<code>VARCHAR</code>列的文本增加前缀，下一次从数据记录中获取这些记录的时候要重新去掉前缀。这样定义类型就可以给那些系统中已经存在的旧数据进行标识，表示这类数据在新应用中并没什么用或者不太重要。</p>
<p>了解了四类数据类型之后，我们来看看如果用元数据组织数据库的结构。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="Metadata">Metadata<a class="anchor-link" href="sqlalchemy-introduce.html#Metadata">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>元数据用于把数据库结构集成在一起方便SQLAlchemy快速对接。可以把元数据看成是一种表目录，再加一些引擎和链接的信息。这些信息可以通过<code>MetaData.tables</code>查看。读操作是线程安全的，但是，表的建立不完全是线程安全的。元数据使用之前需要导入并初始化。下面让我们建立一个<code>Metadata</code>对象，为本章后面的例子建立容器来盛放数据库的信息目录。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [1]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">MetaData</span>
<span class="n">metadata</span> <span class="o">=</span> <span class="n">MetaData</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>有了盛放数据库结构的地方，我们就可以建立数据表了。</p>
<h3 id="Tables">Tables<a class="anchor-link" href="sqlalchemy-introduce.html#Tables">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>在SQLAlchemy Core里数据表对象初始化过程是通过<code>Table</code>通过表名称，元数据和数据列的名称，类型和属性共同构建，最终放入<code>MetaData</code>对象的。列对象表示数据表的每个字段，都是用包含名称、数据类型和一些SQL结构与约束特征的<code>Column</code>对象表示。我们将从这里开始建立一些数据表在SQLAlchemy Core部分使用。例2-1如下所示，建立一个网店的饼干库存表。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [2]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">Table</span><span class="p">,</span> <span class="n">Column</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">,</span> <span class="n">String</span><span class="p">,</span> <span class="n">ForeignKey</span>

<span class="n">cookies</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'cookies'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_name'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">),</span> <span class="n">index</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_recipe_url'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">255</span><span class="p">)),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'quantity'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'unit_cost'</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
            
<span class="p">)</span>

<span class="nb">list</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[2]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[Column('cookie_id', Integer(), table=&lt;cookies&gt;, primary_key=True, nullable=False),
 Column('cookie_name', String(length=50), table=&lt;cookies&gt;),
 Column('cookie_recipe_url', String(length=255), table=&lt;cookies&gt;),
 Column('quantity', Integer(), table=&lt;cookies&gt;),
 Column('unit_cost', Numeric(precision=12, scale=2), table=&lt;cookies&gt;)]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>建立新表之前，我们需要理解表的基础单元——列。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="Columns">Columns<a class="anchor-link" href="sqlalchemy-introduce.html#Columns">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>列定义了数据表中的字段，它们通过我们对其关键词参数的设置来表达具体的含义。不同类型的主要参数不同。例如，字符串类型的基本参数是长度，而带小数的数值类型基本参数是精度和长度。其他类型大都没有基本参数。</p>
<blockquote>
<p>有时你也会看到字符串类型没有设置长度。并非所有的数据库都支持这种特性，包括MySQL也不支持。</p>
</blockquote>
<p>列也有一些别的参数来帮助它们建立更丰富的特性。我们可以为列设置是否允许空值或必须具有唯一性（<code>unique</code>）。还可以定义初始值（<code>default</code>），通常这么做是为了日志记录或财务审计的需要，如下所示。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [3]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">datetime</span>
<span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">DateTime</span>
<span class="n">users</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'users'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'user_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'username'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">15</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'email_address'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">255</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'phone'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">20</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'password'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">25</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'created_on'</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">(),</span> <span class="n">default</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'updated_on'</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">(),</span> <span class="n">default</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">,</span> <span class="n">onupdate</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">)</span>
<span class="p">)</span>

<span class="nb">list</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[3]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[Column('user_id', Integer(), table=&lt;users&gt;, primary_key=True, nullable=False),
 Column('username', String(length=15), table=&lt;users&gt;, nullable=False),
 Column('email_address', String(length=255), table=&lt;users&gt;, nullable=False),
 Column('phone', String(length=20), table=&lt;users&gt;, nullable=False),
 Column('password', String(length=25), table=&lt;users&gt;, nullable=False),
 Column('created_on', DateTime(), table=&lt;users&gt;, default=ColumnDefault(&lt;function ColumnDefault._maybe_wrap_callable.&lt;locals&gt;.&lt;lambda&gt; at 0x0000000005AD3730&gt;)),
 Column('updated_on', DateTime(), table=&lt;users&gt;, onupdate=ColumnDefault(&lt;function ColumnDefault._maybe_wrap_callable.&lt;locals&gt;.&lt;lambda&gt; at 0x0000000005AD3950&gt;), default=ColumnDefault(&lt;function ColumnDefault._maybe_wrap_callable.&lt;locals&gt;.&lt;lambda&gt; at 0x0000000005AD38C8&gt;))]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<blockquote>
<p>你会发现这里使用<code>datatime.now</code>，而不是<code>datatime.now()</code>。如果我们直接用函数，那么时间可能就是数据表第一次建立的时间。不带<code>()</code>我们就可以在每条记录生成时产生一个新的时间。</p>
</blockquote>
<p>我们通过列关键词参数定义了数据表的结构和约束；但是，列对象有时可能需要和其他表进行关联。当你处理数据库时，你必须告诉SQLAlchemy关于这个数据库内部的模式，结构和约束。假如有一个数据库和SQLAlchemy使用的索引名称模式不同，那么你必须定义索引才能正常使用。下面两个小节将告诉你怎么做。</p>
<blockquote>
<p><em>Keys and Constraints</em>和<em>Index</em>两节的程序其实都可以在<code>Table</code>构造函数里直接实现，也可以通过特定方法在表建立之后实现，再增加到表中。它们都会作为单独一行语句保存到<code>metadata</code>里面。</p>
</blockquote>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="Keys-and-Constraints">Keys and Constraints<a class="anchor-link" href="sqlalchemy-introduce.html#Keys-and-Constraints">¶</a>
</h4>
<p>键和约束是用来保证数据在存到数据库之前能够满足一些约束条件的方法。表示键和约束的对象在SQLAlchemy模块里面都有，常用的三个如下所示：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">PrimaryKeyConstraint</span><span class="p">,</span> <span class="n">UniqueConstraint</span><span class="p">,</span> <span class="n">CheckConstraint</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>主键是最常用的，表示数据表中一条记录的唯一标识，可以用来保证不同表里相关数据之间正确的关系。前面的例1和例2中，我们用<code>primary_key</code>参数将一列设置为主键。你还可以用若干列构成的元组来定义一个复合主键。这个键在表中被看成是一个内容为元组的列，会按照它们原始顺序进行排列。主键还可以在表构建之后再定义，如下所示。你可以用逗号分隔，增加多列形成一个复合主键。如果我们想在上面例2中显示定义主键，可以这样做：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">PrimaryKeyConstraint</span><span class="p">(</span><span class="s1">'user_id'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">'user_pk'</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>另一个常用的约束就是唯一性约束，确保一个字段里任意两个值不重复，如果在登录系统里面出现两个用户名是一样的，那就麻烦了。我们也可以用下面的方式定义例2中用户名列的唯一性约束：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">UniqueConstraint</span><span class="p">(</span><span class="s1">'username'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">'uix_username'</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>例2里没有用到检查约束类型。这种约束类型是用来保证一列数据与用户定义的条件一致。下面的例子，我们保证<code>unit_cost</code>列永远非负，因为成本不可能小于0。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">CheckConstraint</span><span class="p">(</span><span class="s1">'unit_coust &gt;= 0.00'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">'unit_coust_positive'</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>除了键和约束，我们还想更高效的查询一些字段。这就要介绍索引（Indexes）。</p>
<h4 id="Indexes">Indexes<a class="anchor-link" href="sqlalchemy-introduce.html#Indexes">¶</a>
</h4>
<p>索引是用来加速查询的，在例1里面，我们把<code>cookie_name</code>加上了索引，因为我们知道我们经常需要查询它们。索引创建之后你就会获得一个<code>ix_cookies_cookie_name</code>索引。我们也可以显式定义一个索引。多列的索引可以通过分号分隔名称来建立。你还可以增加一个参数<code>unique=True</code>来保证索引具有唯一性。如果显式声明索引，它们就会在放在对应列后面。下面的做法与例1相同：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">Index</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">Index</span><span class="p">(</span><span class="s1">'ix_cookies_cookie_name'</span><span class="p">,</span> <span class="s1">'cookie_name'</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>我们还可以创建了函数索引，不同的数据库可能用法上会有点儿变化。这样可以让你为一些经常查询不常用信息的需求创建检索。例如，如果你想从饼干的SKU号和名称的组合中找<code>SKU0001 Chocolate Chip</code>信息。我们就可以建立一个复合索引来查询：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">Index</span><span class="p">(</span><span class="s1">'ix_test'</span><span class="p">,</span> <span class="n">mytable</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_sku</span><span class="p">,</span> <span class="n">mytable</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>下面到了关系型数据库最重要的部分了，就是表的关联关系与定义。</p>
<h4 id="Relationships-and-ForeignKeyConstraints">Relationships and ForeignKeyConstraints<a class="anchor-link" href="sqlalchemy-introduce.html#Relationships-and-ForeignKeyConstraints">¶</a>
</h4>
<p>现在我们有了一个约束和索引都正确的表，让我们看看表之间的关系如何建立。我们需要一种方法来跟踪订单，包括记录已销售的饼干和数量的信息。表关系图如下所示：
<img src="relationship.png" alt="">
例3实现了<code>line_items</code>表<code>order_id</code>列的关系，就是用<code>ForeignKeyConstraint</code>定义两个表的关系。在本例中，我们有很多<code>line_items</code>表示单个订单。但是，如果你深入到这些订单中，你会发现订单与<code>cookies</code>表的<code>cookie_id</code>外键有关联关系。这是因为<code>line_items</code>表其实与<code>orders</code>和<code>cookies</code>表的一些数据都有关联。关联表用来表示另外两个表之间的多对多关系。通常一个外键用来表示一对多关系，但是如果一个表有多个外键，那么这个表很可能是一个关联表。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">ForeignKey</span><span class="p">,</span> <span class="n">Boolean</span>
<span class="n">orders</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'orders'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
            <span class="n">Column</span><span class="p">(</span><span class="s1">'order_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
            <span class="n">Column</span><span class="p">(</span><span class="s1">'user_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'users.user_id'</span><span class="p">)),</span>
            <span class="n">Column</span><span class="p">(</span><span class="s1">'shipped'</span><span class="p">,</span> <span class="n">Boolean</span><span class="p">(),</span> <span class="n">default</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="p">)</span>
<span class="n">line_items</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'line_items'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'line_items_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'order_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'orders.order_id'</span><span class="p">)),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'cookies.cookie_id'</span><span class="p">)),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'quantity'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'extended_cost'</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="p">)</span>                   
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>用字符串替换实际的列名可以在多个模块中把表的定义分离，这样就不用担心表加载的顺序了。这是因为，它只会在首次连接表名称和列名称的时候解析字符串执行表查询。如果我们直接用表引用，比如<code>cookies.c.cookie_id</code>，我们的外键在每次模块初始化的时候都要执行一次，如果表加载的顺序特别靠后就会出错。</p>
<p>你可以显式的调研<code>ForeignKeyConstraint</code>定义，在SQLAlchemy里面可以对已经建好的表建立外键，就像其他的键，约束和索引的创建一样。需要先倒入<code>ForeignKeyConstraint</code>模块然后定义。下面的代码是创建一个<code>ForeignKeyConstraint</code>表示<code>line_items</code>表和<code>orders</code>之间<code>order_id</code>外键。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">ForeignKeyConstraint</span>

<span class="n">ForeignKeyConstraint</span><span class="p">([</span><span class="s1">'order_id'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'orders.order_id'</span><span class="p">])</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>前面做的每件事情都是用SQLAlchemy可以理解的方式定义的。如果你的数据库已经存在，而且schema已经建立，你就可以进行查询了。如果你还没建立，下面就介绍如何把数据库建成文件。</p>
<h4 id="Persisting-the-Tables">Persisting the Tables<a class="anchor-link" href="sqlalchemy-introduce.html#Persisting-the-Tables">¶</a>
</h4>
<p>表和模式定义与原数据相关。把模式保存到数据库很简单，用<code>metadata</code>的<code>create_all()</code>方法就可以了：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">metadata</span><span class="o">.</span><span class="n">create_all</span><span class="p">(</span><span class="n">engine</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>默认情况下，<code>create_all()</code>方法不会重新创建已经存在的数据库，所有运行多次也很安全。相比直接在应用代码里修改数据库，用Alembic那样的迁移工具处理数据库的更新或其他模式是更好的方法。我们将在后面的章节里介绍。现在数据库里面已经有表了，这一章完整的代码如下所示：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [7]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">datetime</span>
<span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="p">(</span><span class="n">MetaData</span><span class="p">,</span> <span class="n">Table</span><span class="p">,</span> <span class="n">Column</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">,</span> <span class="n">String</span><span class="p">,</span>
                        <span class="n">Boolean</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">,</span> <span class="n">create_engine</span><span class="p">)</span>
<span class="n">metadata</span> <span class="o">=</span> <span class="n">MetaData</span><span class="p">()</span>
<span class="n">cookies</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'cookies'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_name'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">),</span> <span class="n">index</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_recipe_url'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">255</span><span class="p">)),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_sku'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">55</span><span class="p">)),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'quantity'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'unit_cost'</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
                <span class="p">)</span>
<span class="n">users</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'users'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'user_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'customer_number'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">autoincrement</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'username'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">15</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'email_address'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">255</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'phone'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">20</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'password'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">25</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'created_on'</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">(),</span> <span class="n">default</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'updated_on'</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">(),</span>
                     <span class="n">default</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">,</span> <span class="n">onupdate</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">)</span>
              <span class="p">)</span>
<span class="n">orders</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'orders'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
               <span class="n">Column</span><span class="p">(</span><span class="s1">'order_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
               <span class="n">Column</span><span class="p">(</span><span class="s1">'user_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'users.user_id'</span><span class="p">)),</span>
               <span class="n">Column</span><span class="p">(</span><span class="s1">'shipped'</span><span class="p">,</span> <span class="n">Boolean</span><span class="p">(),</span> <span class="n">default</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
               <span class="p">)</span>
<span class="n">line_items</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'line_items'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'line_items_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'order_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'orders.order_id'</span><span class="p">)),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'cookies.cookie_id'</span><span class="p">)),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'quantity'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'extended_cost'</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
                   <span class="p">)</span>
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s1">'sqlite:///:memory:'</span><span class="p">)</span>
<span class="n">metadata</span><span class="o">.</span><span class="n">create_all</span><span class="p">(</span><span class="n">engine</span><span class="p">)</span>
<span class="n">connection</span> <span class="o">=</span> <span class="n">engine</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>本章我们介绍了如何在SQLAlchemy里把元数据当作目录（catalog）来存放表模式和其他数据。我们还定义了带有多列和多约束的表。然后，我们介绍约束的类型和这些约束对列进行的显式定义的方法。其次，我们介绍了默认值的设置和为了查账进行更新值的方法。最后，我们介绍了把模式保存到数据库进行重用的方法。下面我们介绍如何在模式中用SQL表达式语言进行数据的操作。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="3.SQLAlchemy-Core数据操作">3.SQLAlchemy Core数据操作<a class="anchor-link" href="sqlalchemy-introduce.html#3.SQLAlchemy-Core%E6%95%B0%E6%8D%AE%E6%93%8D%E4%BD%9C">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在数据库里面有了表，让我们来操作它们。首先我们将演示如何增删改查，然后介绍如果排序，组合以及如何使用关系。我们用SQLAlchemy Core提供的SEL（SQL表达式语言）演示。还是用上一章建立的数据库，首先我们看看如何新建数据。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="Inserting-Data">Inserting Data<a class="anchor-link" href="sqlalchemy-introduce.html#Inserting-Data">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>首先，我们在<code>cookies</code>表新建一行我最喜欢的饼干（巧克力味的）。用<code>cookies</code>表的<code>insert()</code>方法，然后在<code>values()</code>语句里面设置各个列的值就可以了。如下所示：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [8]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">ins</span> <span class="o">=</span> <span class="n">cookies</span><span class="o">.</span><span class="n">insert</span><span class="p">()</span><span class="o">.</span><span class="n">values</span><span class="p">(</span>
    <span class="n">cookie_name</span><span class="o">=</span><span class="s2">"chocolate chip"</span><span class="p">,</span>
    <span class="n">cookie_recipe_url</span><span class="o">=</span><span class="s2">"http://some.aweso.me/cookie/recipe.html"</span><span class="p">,</span>
    <span class="n">cookie_sku</span><span class="o">=</span><span class="s2">"CC01"</span><span class="p">,</span>
    <span class="n">quantity</span><span class="o">=</span><span class="s2">"12"</span><span class="p">,</span>
    <span class="n">unit_cost</span><span class="o">=</span><span class="s2">"0.50"</span>
<span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">ins</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>INSERT INTO cookies (cookie_name, cookie_recipe_url, cookie_sku, quantity, unit_cost) VALUES (:cookie_name, :cookie_recipe_url, :cookie_sku, :quantity, :unit_cost)
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>上面显示了对应的SQL语句。每一列的值都用<code>:column_name</code>代替了，SQLAlchemy的<code>str()</code>函数就是这样显示的。数值都进行过清洗和转义处理，保证数据安全，避免SQL注入攻击。因为不同种类的数据库处理参数值的方言可能有点差别，所以通过编译版本的语句可以看到输入的内容。<code>ins</code>对象的<code>compile()</code>方法会返回一个SQLAlchemy对象，通过<code>params</code>属性就可以看到数值了。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [9]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">ins</span><span class="o">.</span><span class="n">compile</span><span class="p">()</span><span class="o">.</span><span class="n">params</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[9]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>{'cookie_name': 'chocolate chip',
 'cookie_recipe_url': 'http://some.aweso.me/cookie/recipe.html',
 'cookie_sku': 'CC01',
 'quantity': '12',
 'unit_cost': '0.50'}</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><code>ins.compile()</code>通过方言编译数据，但是并没执行，因此我们需要用<code>params</code>属性查看。</p>
<p>介绍了新建语句的用法之后，我们用<code>connection</code>的<code>execute()</code>方法把数据加入数据表。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [10]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>我们还可以用<code>inserted_primary_key</code>属性查看刚刚新建数据的ID号。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [11]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">result</span><span class="o">.</span><span class="n">inserted_primary_key</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[11]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[1]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>我们简单介绍一下<code>excute()</code>执行的过程。当我们建立前面那条SQL表达式语言的插入语句时，实际上是创建了一个可以快速向下遍历的树状结构。当我们调用<code>excute()</code>方法时，它把刚刚传入的语句和其他任何参数一起编译成对应数据库方言编译器能够识别的语句。编译器通过遍历那个树状结构建成一个普通的SQL语句。这个语句返回到<code>excute()</code>方法，<code>excute()</code>方法通过绑定的连接把语句传递到数据库。数据库服务器就执行SQL语句然后把结果返回给<code>excute()</code>方法。</p>
<p><code>insert</code>除了可以作为表对象的实例方法，也可以当作顶层函数使用，这样可以把表对象作为参数，更具灵活性。例如，假如公司的两个部门分别拥有相互独立的库存数据，就可以按照例3-3的形式再插入一行数据。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [12]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">insert</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">cookies</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span>
    <span class="n">cookie_name</span><span class="o">=</span><span class="s2">"chocolate chip"</span><span class="p">,</span>
    <span class="n">cookie_recipe_url</span><span class="o">=</span><span class="s2">"http://some.aweso.me/cookie/recipe.html"</span><span class="p">,</span>
    <span class="n">cookie_sku</span><span class="o">=</span><span class="s2">"CC01"</span><span class="p">,</span>
    <span class="n">quantity</span><span class="o">=</span><span class="s2">"12"</span><span class="p">,</span>
    <span class="n">unit_cost</span><span class="o">=</span><span class="s2">"0.50"</span>
<span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<blockquote>
<p>虽然<code>insert</code>的表对象方法和更具一般性的函数两种形式结果一样，我还是更喜欢后者，因为它更接近SQL语句的用法。</p>
</blockquote>
<p>连接对象的<code>execute()</code>方法不仅仅只是处理语句，还可以把<code>values</code>当作<code>execute()</code>方法的参数。当语句被编译时，它会把每个关键词参数的键增加到字段列表中，然后再把每个字段对应的值增加到SQL语句的<code>VALUE</code>参数里。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [13]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">ins</span> <span class="o">=</span> <span class="n">cookies</span><span class="o">.</span><span class="n">insert</span><span class="p">()</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
    <span class="n">ins</span><span class="p">,</span>
    <span class="n">cookie_name</span><span class="o">=</span><span class="s1">'dark chocolate chip'</span><span class="p">,</span>
    <span class="n">cookie_recipe_url</span><span class="o">=</span><span class="s1">'http://some.aweso.me/cookie/recipe_dark.html'</span><span class="p">,</span>
    <span class="n">cookie_sku</span><span class="o">=</span><span class="s1">'CC02'</span><span class="p">,</span>
    <span class="n">quantity</span><span class="o">=</span><span class="s1">'1'</span><span class="p">,</span>
    <span class="n">unit_cost</span><span class="o">=</span><span class="s1">'0.75'</span>
<span class="p">)</span>
<span class="n">result</span><span class="o">.</span><span class="n">inserted_primary_key</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[13]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[2]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>不过这种形式并不常用，但是，它为语句在传到数据库服务器之前的编译和组织方式提供了一个很好的解释。我们可以用放了字段和数值词典的列表一次性插入多个记录。让我们把两种饼干的库存数据插入<code>cookies</code>表。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [14]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">ins</span> <span class="o">=</span> <span class="n">cookies</span><span class="o">.</span><span class="n">insert</span><span class="p">()</span>
<span class="n">inventory_list</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s1">'cookie_name'</span><span class="p">:</span> <span class="s1">'peanut butter'</span><span class="p">,</span>
        <span class="s1">'cookie_recipe_url'</span><span class="p">:</span> <span class="s1">'http://some.aweso.me/cookie/peanut.html'</span><span class="p">,</span>
        <span class="s1">'cookie_sku'</span><span class="p">:</span> <span class="s1">'PB01'</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="s1">'24'</span><span class="p">,</span>
        <span class="s1">'unit_cost'</span><span class="p">:</span> <span class="s1">'0.25'</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">'cookie_name'</span><span class="p">:</span> <span class="s1">'oatmeal raisin'</span><span class="p">,</span>
        <span class="s1">'cookie_recipe_url'</span><span class="p">:</span> <span class="s1">'http://some.okay.me/cookie/raisin.html'</span><span class="p">,</span>
        <span class="s1">'cookie_sku'</span><span class="p">:</span> <span class="s1">'EWW01'</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="s1">'100'</span><span class="p">,</span>
        <span class="s1">'unit_cost'</span><span class="p">:</span> <span class="s1">'1.00'</span>
    <span class="p">}</span>
<span class="p">]</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">,</span> <span class="n">inventory_list</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<blockquote>
<p>列表中的每个词典都要有同样的键（<code>keys</code>）。首先方言编译器会编译第一个词典的语句内容，如果后面词典的键与第一条不同就会失败，因为第一条的字段已经建好了。</p>
</blockquote>
<p>现在有了数据，我们就可以查询了。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="Querying-Data">Querying Data<a class="anchor-link" href="sqlalchemy-introduce.html#Querying-Data">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [15]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy.sql</span> <span class="k">import</span> <span class="n">select</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="p">])</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">results</span> <span class="o">=</span> <span class="n">rp</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="n">results</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stderr output_text">
<pre>d:\Miniconda3\lib\site-packages\sqlalchemy\sql\sqltypes.py:565: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.
  'storage.' % (dialect.name, dialect.driver))
</pre>
</div>
</div>

<div class="output_area">
<div class="prompt output_prompt">Out[15]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[(1, 'chocolate chip', 'http://some.aweso.me/cookie/recipe.html', 'CC01', 12, Decimal('0.50')),
 (2, 'dark chocolate chip', 'http://some.aweso.me/cookie/recipe_dark.html', 'CC02', 1, Decimal('0.75')),
 (3, 'peanut butter', 'http://some.aweso.me/cookie/peanut.html', 'PB01', 24, Decimal('0.25')),
 (4, 'oatmeal raisin', 'http://some.okay.me/cookie/raisin.html', 'EWW01', 100, Decimal('1.00'))]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [16]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">s</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>SELECT cookies.cookie_id, cookies.cookie_name, cookies.cookie_recipe_url, cookies.cookie_sku, cookies.quantity, cookies.unit_cost 
FROM cookies
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>和<code>insert</code>用法类似，<code>select</code>也是既可以作为表对象的实例方法，也可以作为更具一般性的顶层函数使用。我更喜欢顶层函数的使用方式，因为和SQL用法一样。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [17]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy.sql</span> <span class="k">import</span> <span class="n">select</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">cookies</span><span class="o">.</span><span class="n">select</span><span class="p">()</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">results</span> <span class="o">=</span> <span class="n">rp</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="n">results</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[17]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[(1, 'chocolate chip', 'http://some.aweso.me/cookie/recipe.html', 'CC01', 12, Decimal('0.50')),
 (2, 'dark chocolate chip', 'http://some.aweso.me/cookie/recipe_dark.html', 'CC02', 1, Decimal('0.75')),
 (3, 'peanut butter', 'http://some.aweso.me/cookie/peanut.html', 'PB01', 24, Decimal('0.25')),
 (4, 'oatmeal raisin', 'http://some.okay.me/cookie/raisin.html', 'EWW01', 100, Decimal('1.00'))]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="ResultProxy">ResultProxy<a class="anchor-link" href="sqlalchemy-introduce.html#ResultProxy">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>ResultProxy是对数据库API光标对象的封装，其主要目的是让数据操作更简单。例如，它可以通过索引，字段名称和列对象让查询操作更简单，演示如例3-8所示。任何一种方法查询数据都很简单。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [18]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">first_row</span> <span class="o">=</span> <span class="n">results</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [19]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">first_row</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[19]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>'chocolate chip'</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [20]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">first_row</span><span class="o">.</span><span class="n">cookie_name</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[20]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>'chocolate chip'</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [21]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">first_row</span><span class="p">[</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">]</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[21]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>'chocolate chip'</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>上面的输出结果都是<code>results</code>变量第一个记录的数据<code>chocolate chip</code>。接入灵活只是ResultProxy能力的一部分。我们还可以用ResultProxy实现循环。例如，我们可以打印所有饼干的名称。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [22]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">for</span> <span class="n">record</span> <span class="ow">in</span> <span class="n">rp</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">record</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>chocolate chip
dark chocolate chip
peanut butter
oatmeal raisin
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>ResultProxy除了可以循环，或调用<code>fetchall()</code>方法之外，很多其他数据接入方式也可以用。其实，上例中所有的<code>result</code>变量所有的插入数据操作都是用ResultProxy实现的。<code>rowcount()</code>和<code>inserted_primary_key()</code>方法也是ResultProxy获取信息的一种方式。你也可以用下面的方法获取信息：</p>
<ul>
<li>first()——如果存在则返回第一条记录并关闭连接</li>
<li>fetchone()——返回一条记录，光标继续开着，等待新的查询</li>
<li>scalar()——如果查询结果只有一行一列，就返回一个值</li>
</ul>
<p>如果要看结果中所有列名，可以用<code>keys()</code>方法。后面的章节里，我们还会经常使用<code>first</code>，<code>scalar</code>，<code>fetchone</code>，<code>fetchall</code>方法和ResultProxy循环。</p>
<blockquote>
<p>产品代码
写产品代码的时候，我有几条原则：</p>
<ul>
<li>用<code>first</code>获取一条记录，不用<code>scalar</code>和<code>fetchone</code>，因为这样更清晰</li>
<li>用ResultProxy循环，不用<code>fetchall</code>和<code>fetchone</code>方法。这样内存开销更新，因为通常我们都是一次处理一条记录</li>
<li>尽量不要用<code>fetchone</code>，因为它会让连接一直开着</li>
<li>
<code>scalar</code>也要少用，因为当查询返回多余一行一列数据的时候容易出错，这一点在测试的时候经常被忽略</li>
</ul>
</blockquote>
<p>在上例中，每一次我们查询数据集的时候每条记录的所有列都会返回。而通常我们只需要一部分列就可以。如果数据非常大，这样查询就会非常耗费内存，查询速度就会很慢。SQLAlchemy不会为查询或ResultProxy增加负担；但是，通常查询完成后，你需要看看查询是否消耗了太多内存。下面我们就来介绍如何控制查询的范围。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="控制查询的列">控制查询的列<a class="anchor-link" href="sqlalchemy-introduce.html#%E6%8E%A7%E5%88%B6%E6%9F%A5%E8%AF%A2%E7%9A%84%E5%88%97">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>可以用<code>select()</code>方法将要查询的列以列表形式放入。例如，下面代码是只需要查看饼干的名称和质量时的操作。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [23]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">rp</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">rp</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>['cookie_name', 'quantity']
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [24]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">result</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[24]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>('chocolate chip', 12)</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这样我们就建立了简单的<code>select</code>语句，我们将看看其他改变选择结果的操作。首先我们看看如何改变顺序。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Ordering">Ordering<a class="anchor-link" href="sqlalchemy-introduce.html#Ordering">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>如果在上面例10中你要查看所有的数据结果，你会发现名称排序很混乱。但是，如果我们想让名称按照指定顺序排列，可用<code>select</code>的<code>order_by()</code>语句。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [25]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">)</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">for</span> <span class="n">cookie</span> <span class="ow">in</span> <span class="n">rp</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{}</span><span class="s1"> - </span><span class="si">{}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">cookie</span><span class="o">.</span><span class="n">quantity</span><span class="p">,</span> <span class="n">cookie</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>1 - dark chocolate chip
12 - chocolate chip
24 - peanut butter
100 - oatmeal raisin
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>如果要逆序排列，就在<code>order_by()</code>里面增加<code>desc()</code>。用<code>desc()</code>包裹排序参数即可。</p>
<blockquote>
<p><code>desc()</code>也可以当成列对象的方法来使用，</p>
</blockquote>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [26]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">desc</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="n">desc</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">))</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">for</span> <span class="n">cookie</span> <span class="ow">in</span> <span class="n">rp</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{}</span><span class="s1"> - </span><span class="si">{}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">cookie</span><span class="o">.</span><span class="n">quantity</span><span class="p">,</span> <span class="n">cookie</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>100 - oatmeal raisin
24 - peanut butter
12 - chocolate chip
1 - dark chocolate chip
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>还可以限制查询记录结果的数量。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Limiting">Limiting<a class="anchor-link" href="sqlalchemy-introduce.html#Limiting">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>前面的例子里，<code>first()</code>和<code>fetchone()</code>方法是用来获得一行记录的。ResultProxy可以提供一行数据，实际中我们经常需要多行数据。如果我们想限制查询数量，我们可以用<code>limit()</code>函数。例如，如果我现在想做销量最好的两种饼干，那么对排序后的查询增加一个限制条件就可以了。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [27]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">limit</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="nb">print</span><span class="p">([</span><span class="n">result</span><span class="o">.</span><span class="n">cookie_name</span> <span class="k">for</span> <span class="n">result</span> <span class="ow">in</span> <span class="n">rp</span><span class="p">])</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>['dark chocolate chip', 'chocolate chip']
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在我们知道饼干的种类了，我开始关心库存还有多少。很多数据库都有一堆SQL函数对数据进行统计，必然SUM等等，让我们看看这些函数如何使用。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Builtin-SQL-Functions-and-Labels">Builtin SQL Functions and Labels<a class="anchor-link" href="sqlalchemy-introduce.html#Builtin-SQL-Functions-and-Labels">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>SQLAlchemy的SQL函数里最常用的是<code>SUM()</code>和<code>COUNT()</code>。使用这个函数之前我们需要导入<code>sqlalchemy.sql.func</code>模块，这些函数只要包裹列对象就可以运行。所以要统计饼干的总量，我们可以这样：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [28]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">func</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">func</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">)])</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">rp</span><span class="o">.</span><span class="n">scalar</span><span class="p">())</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>137
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<blockquote>
<p>因为Python内置函数也有<code>sum</code>，所以使用SQLAlchemy的<code>sum</code>时，建议导入<code>func</code>用<code>func.sum</code>。</p>
</blockquote>
<p>现在让我们用<code>count</code>函数统计<code>cookie</code>表里有多少条库存记录。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [29]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">)])</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">record</span> <span class="o">=</span> <span class="n">rp</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="n">record</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span> <span class="c1"># 显示Resultproxy里的列</span>
<span class="nb">print</span><span class="p">(</span><span class="n">record</span><span class="o">.</span><span class="n">count_1</span><span class="p">)</span> <span class="c1"># 列名是自动生成的，命名方式是`&lt;函数名&gt;_&lt;位置&gt;`</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>['count_1']
4
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这个列名有点隐蔽。如果我们想自定义名称，也可以用在<code>count()</code>函数后用<code>label()</code>函数来定义列名。例如，我们想用更好记的名称来定义记录数量。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [30]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">)</span><span class="o">.</span><span class="n">label</span><span class="p">(</span><span class="s1">'inventory_count'</span><span class="p">)])</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">record</span> <span class="o">=</span> <span class="n">rp</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="n">record</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="nb">print</span><span class="p">(</span><span class="n">record</span><span class="o">.</span><span class="n">inventory_count</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>['inventory_count']
4
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>介绍了如何限制行和列的数量之后，我们再看看如何进行数据过滤。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Filtering">Filtering<a class="anchor-link" href="sqlalchemy-introduce.html#Filtering">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>过滤查询和SQL一样用<code>where()</code>函数来实现。通常<code>where()</code>函数有一个列名称，一个操作符和一个值或列。也可以用连接多个<code>where()</code>语句，像SQL里面逻辑操作符<code>AND</code>的作用。下面我们来找名称为<code>chocolate chip</code>的饼干。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [31]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="p">])</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span> <span class="o">==</span> <span class="s1">'chocolate chip'</span><span class="p">)</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">record</span> <span class="o">=</span> <span class="n">rp</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
<span class="n">record</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="c1"># 显示所有列名和数值</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[31]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[('cookie_id', 1),
 ('cookie_name', 'chocolate chip'),
 ('cookie_recipe_url', 'http://some.aweso.me/cookie/recipe.html'),
 ('cookie_sku', 'CC01'),
 ('quantity', 12),
 ('unit_cost', Decimal('0.50'))]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>我们还可以用<code>where()</code>找包含<code>chocolate</code>的饼干名称。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [32]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="p">])</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="o">.</span><span class="n">like</span><span class="p">(</span><span class="s1">'</span><span class="si">%c</span><span class="s1">hocolate%'</span><span class="p">))</span>
<span class="n">rp</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">for</span> <span class="n">record</span> <span class="ow">in</span> <span class="n">rp</span><span class="o">.</span><span class="n">fetchall</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">record</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>chocolate chip
dark chocolate chip
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><code>where()</code>语句里我们用<code>cookies.c.cookie_name</code>作为过滤的<code>ClauseElement</code>类型。我们现在停下来，看看<code>ClauseElement</code>类型的其他功能。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Operators">Operators<a class="anchor-link" href="sqlalchemy-introduce.html#Operators">¶</a>
</h5>
<p>ClauseElements就是我们在从句中使用的一个元素，通常都是数据表的列；但是，和列不同，ClauseElements有许多功能。在例3-18里面，我们用来<code>like()</code>方法，其实还有很多方法如表3-1所示。每个方法都和标准SQL里面的函数类似。后面会大量使用它们。</p>
<table>
<thead><tr>
<th style="text-align:center">方法</th>
<th style="text-align:center">目的</th>
</tr></thead>
<tbody>
<tr>
<td style="text-align:center"><code>between(cleft, cright)</code></td>
<td style="text-align:center">Find where the column is between cleft and cright</td>
</tr>
<tr>
<td style="text-align:center"><code>concat(column_two)</code></td>
<td style="text-align:center">Concatenate column with column_two</td>
</tr>
<tr>
<td style="text-align:center"><code>distinct()</code></td>
<td style="text-align:center">Find only unique values for column</td>
</tr>
<tr>
<td style="text-align:center"><code>in_([list])</code></td>
<td style="text-align:center">Find where the column is in the list</td>
</tr>
<tr>
<td style="text-align:center"><code>is_(None)</code></td>
<td style="text-align:center">Find where the column is None (commonly used for Null checks with None)</td>
</tr>
<tr>
<td style="text-align:center"><code>contains(string)</code></td>
<td style="text-align:center">Find where the column has string in it (Case-sensitive)</td>
</tr>
<tr>
<td style="text-align:center"><code>endswith(string)</code></td>
<td style="text-align:center">Find where the column ends with string (Case-sensitive)</td>
</tr>
<tr>
<td style="text-align:center"><code>like(string)</code></td>
<td style="text-align:center">Find where the column is like string (Case-sensitive)</td>
</tr>
<tr>
<td style="text-align:center"><code>startswith(string)</code></td>
<td style="text-align:center">Find where the column begins with string (Case-sensitive)</td>
</tr>
<tr>
<td style="text-align:center"><code>ilike(string)</code></td>
<td style="text-align:center">Find where the column is like string (NOT Case-sensitive)</td>
</tr>
</tbody>
</table>
<p>还有两个相反操作的函数<code>notlike()</code>和<code>notin_()</code>，以及一个不带下划线的函数<code>isnot()</code>。</p>
<p>如果我们不用这些方法，我们还可以用运算符。大部分运算符都和你的习惯一样，不过我们要介绍一些奇怪的地方。</p>
<h5 id="操作符">操作符<a class="anchor-link" href="sqlalchemy-introduce.html#%E6%93%8D%E4%BD%9C%E7%AC%A6">¶</a>
</h5>
<p>到目前为止我们过滤数据都是通过判断列是否等于一个数值，或者用ClauseElement方法的函数，比如<code>like()</code>；其实我们还可以用很多运算符号来过滤数据。SQLAlchemy提供了大量Python的标准运算符。这包括所有的标准比较运算符（<code>==</code>，<code>!=</code>，<code>&lt;</code>，<code>&gt;</code>，<code>&gt;=</code>），与Python语句里使用方法一致。<code>==</code>操作符在和<code>None</code>比较时还表示<code>IS NULL</code>。算法运算符（<code>+</code>,<code>-</code>,<code>*</code>,<code>/</code>,<code>%</code>）也可用于数据库字符串处理，如例3-19所示。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [33]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="s1">'SKU-'</span> <span class="o">+</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_sku</span><span class="p">])</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>('chocolate chip', 'SKU-CC01')
('dark chocolate chip', 'SKU-CC02')
('peanut butter', 'SKU-PB01')
('oatmeal raisin', 'SKU-EWW01')
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>另一个常用操作就是计算多列的数值。通常做财务和统计报表时经常用到，例3-20计算库存金额：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [34]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">cast</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span>
            <span class="n">cast</span><span class="p">((</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span> <span class="o">*</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">unit_cost</span><span class="p">),</span>
                 <span class="n">Numeric</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span><span class="mi">2</span><span class="p">))</span><span class="o">.</span><span class="n">label</span><span class="p">(</span><span class="s1">'inv_cost'</span><span class="p">)])</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{}</span><span class="s1"> - </span><span class="si">{}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">row</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">row</span><span class="o">.</span><span class="n">inv_cost</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>chocolate chip - 6.00
dark chocolate chip - 0.75
peanut butter - 6.00
oatmeal raisin - 100.00
</pre>
</div>
</div>

<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stderr output_text">
<pre>d:\Miniconda3\lib\site-packages\sqlalchemy\sql\sqltypes.py:565: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.
  'storage.' % (dialect.name, dialect.driver))
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Boolean-Operators">Boolean Operators<a class="anchor-link" href="sqlalchemy-introduce.html#Boolean-Operators">¶</a>
</h5>
<p>SQLAlchemy也支持逻辑运算符（与AND，或OR，非NOT），用位操作符表示（<code>&amp;</code>，<code>|</code>，<code>~</code>）。使用时一定要注意，因为Python自带的逻辑运算符规则。比如，<code>&amp;</code>比<code>&lt;</code>优先级高，当你写<code>A &lt; B &amp; C &lt; D</code>的时候，运算结果是<code>A &lt; (B &amp; C) &lt; D</code>，而你实际想写的是<code>(A &lt; B) &amp; (C &lt; D)</code>。为了清晰表达意思，请用连接词（conjunctions），不要用这些重载运算符。</p>
<p>通常在处理多个从句时，从句之间存在与或非关系时，应该用连接词。</p>
<h5 id="Conjunctions">Conjunctions<a class="anchor-link" href="sqlalchemy-introduce.html#Conjunctions">¶</a>
</h5>
<p>虽然可以把多个<code>where()</code>从句连起来，但是用连接词会让语句更清晰好看。SQLAlchemy的连接词是<code>and_()</code>，<code>or_()</code>和<code>not_()</code>。如果我们想要查询库存和单价满足特定条件的饼干时，可以用<code>and_()</code>实现。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [35]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">and_</span><span class="p">,</span> <span class="n">or_</span><span class="p">,</span> <span class="n">not_</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="p">])</span><span class="o">.</span><span class="n">where</span><span class="p">(</span>
    <span class="n">and_</span><span class="p">(</span>
        <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span> <span class="o">&gt;</span> <span class="mi">23</span><span class="p">,</span>
        <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">unit_cost</span> <span class="o">&lt;</span> <span class="mf">0.40</span>
    <span class="p">)</span>
<span class="p">)</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>peanut butter
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><code>or_()</code>函数与<code>and_()</code>相反，包含任何一种情形就可以。如果我们想找到库存在10到50之间，或名称包含<em>chip</em>的饼干时，可以用<code>or_</code>。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [36]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">and_</span><span class="p">,</span> <span class="n">or_</span><span class="p">,</span> <span class="n">not_</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="p">])</span><span class="o">.</span><span class="n">where</span><span class="p">(</span>
    <span class="n">or_</span><span class="p">(</span>
        <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="o">.</span><span class="n">between</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">50</span><span class="p">),</span>
        <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="o">.</span><span class="n">contains</span><span class="p">(</span><span class="s1">'chip'</span><span class="p">)</span>
    <span class="p">)</span>
<span class="p">)</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>chocolate chip
dark chocolate chip
peanut butter
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><code>not()</code>连接词类似，只是表示不包含条件的结果。到这里我们已经可以轻松的查询数据了，下面我们看看如何更新数据。</p>
<h4 id="Updating-Data">Updating Data<a class="anchor-link" href="sqlalchemy-introduce.html#Updating-Data">¶</a>
</h4>
<p>还有一个数据更新方法，和前面用的<code>insert</code>方法类似，除了它们需要指定一个条件表面要更新的行，语法与<code>insert</code>完全一致。更新方法可以用<code>update()</code>函数或待更新表的<code>update()</code>方法。如果不增加条件，就会更新表中所有行。当我做完新的饼干之后，就要更新库存数据。在例3-23中，我们更新对应饼干的库存，然后计算新的总库存量。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [37]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">update</span>
<span class="n">u</span> <span class="o">=</span> <span class="n">update</span><span class="p">(</span><span class="n">cookies</span><span class="p">)</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span> <span class="o">==</span> <span class="s1">'chocolate chip'</span><span class="p">)</span>
<span class="n">u</span> <span class="o">=</span> <span class="n">u</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">quantity</span><span class="o">=</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span> <span class="o">+</span> <span class="mi">120</span><span class="p">))</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">result</span><span class="o">.</span><span class="n">rowcount</span><span class="p">)</span>

<span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="p">])</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span> <span class="o">==</span> <span class="s2">"chocolate chip"</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
<span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">result</span><span class="o">.</span><span class="n">keys</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{:&gt;20}</span><span class="s1">: </span><span class="si">{}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">result</span><span class="p">[</span><span class="n">key</span><span class="p">]))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>1
           cookie_id: 1
         cookie_name: chocolate chip
   cookie_recipe_url: http://some.aweso.me/cookie/recipe.html
          cookie_sku: CC01
            quantity: 132
           unit_cost: 0.50
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>除了更新数据，还要删除数据。</p>
<h4 id="Deleting-Data">Deleting Data<a class="anchor-link" href="sqlalchemy-introduce.html#Deleting-Data">¶</a>
</h4>
<p>删除数据可以用<code>delete()</code>函数或表的<code>delete()</code>方法。和<code>insert()</code>，<code>update()</code>不同的是，<code>delete()</code>无数值参数，只有一个可选的<code>where()</code>用于设置删除区域（如果没有就删除全表所有数据）。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [38]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">delete</span>

<span class="n">u</span> <span class="o">=</span> <span class="n">delete</span><span class="p">(</span><span class="n">cookies</span><span class="p">)</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span> <span class="o">==</span> <span class="s1">'dark chocolate chip'</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">result</span><span class="o">.</span><span class="n">rowcount</span><span class="p">)</span>

<span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="p">])</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span> <span class="o">==</span> <span class="s2">"dark chocolate chip"</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">result</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>1
0
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在让我们回想一下所学的知识，对<code>users</code>，<code>orders</code>，<code>line_items</code>表进行更新。你可以直接复制代码，但是建议你试试其他方法新建数据。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [39]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">customer_list</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s1">'username'</span><span class="p">:</span> <span class="s1">'cookiemon'</span><span class="p">,</span>
        <span class="s1">'email_address'</span><span class="p">:</span> <span class="s1">'mon@cookie.com'</span><span class="p">,</span>
        <span class="s1">'phone'</span><span class="p">:</span> <span class="s1">'111-111-1111'</span><span class="p">,</span>
        <span class="s1">'password'</span><span class="p">:</span> <span class="s1">'password'</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">'username'</span><span class="p">:</span> <span class="s1">'cakeeater'</span><span class="p">,</span>
        <span class="s1">'email_address'</span><span class="p">:</span> <span class="s1">'cakeeater@cake.com'</span><span class="p">,</span>
        <span class="s1">'phone'</span><span class="p">:</span> <span class="s1">'222-222-2222'</span><span class="p">,</span>
        <span class="s1">'password'</span><span class="p">:</span> <span class="s1">'password'</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">'username'</span><span class="p">:</span> <span class="s1">'pieguy'</span><span class="p">,</span>
        <span class="s1">'email_address'</span><span class="p">:</span> <span class="s1">'guy@pie.com'</span><span class="p">,</span>
        <span class="s1">'phone'</span><span class="p">:</span> <span class="s1">'333-333-3333'</span><span class="p">,</span>
        <span class="s1">'password'</span><span class="p">:</span> <span class="s1">'password'</span>
    <span class="p">}</span>
<span class="p">]</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">users</span><span class="o">.</span><span class="n">insert</span><span class="p">()</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">,</span> <span class="n">customer_list</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>有了用户数据，让我们再更新他们的<code>orders</code>，<code>line_items</code>表。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [40]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">insert</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">orders</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">user_id</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">order_id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">)</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">line_items</span><span class="p">)</span>
<span class="n">order_items</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s1">'order_id'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
        <span class="s1">'cookie_id'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span>
        <span class="s1">'extended_cost'</span><span class="p">:</span> <span class="mf">1.00</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">'order_id'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
        <span class="s1">'cookie_id'</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="mi">12</span><span class="p">,</span>
        <span class="s1">'extended_cost'</span><span class="p">:</span> <span class="mf">3.00</span>
    <span class="p">}</span>
<span class="p">]</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">,</span> <span class="n">order_items</span><span class="p">)</span>

<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">orders</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">user_id</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">order_id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">)</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">line_items</span><span class="p">)</span>
<span class="n">order_items</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s1">'order_id'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span>
        <span class="s1">'cookie_id'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="mi">24</span><span class="p">,</span>
        <span class="s1">'extended_cost'</span><span class="p">:</span> <span class="mf">12.00</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">'order_id'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span>
        <span class="s1">'cookie_id'</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="mi">6</span><span class="p">,</span>
        <span class="s1">'extended_cost'</span><span class="p">:</span> <span class="mf">6.00</span>
    <span class="p">}</span>
<span class="p">]</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">,</span> <span class="n">order_items</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>在SQLAlchemy Core的第二章中我们介绍过外键和关系；但是我们还没有用它们做过查询，下面我们就来看看这些关系。</p>
<h4 id="Joins">Joins<a class="anchor-link" href="sqlalchemy-introduce.html#Joins">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>用<code>join()</code>和<code>outerjoin()</code>方法进行数据关联。例如，发货之前需要了解用户<code>cookiemon</code>订购了那种饼干。这就需要用3个<code>join</code>来汇总三张表的数据。另外，当用多个<code>join</code>汇总数据时，你可能需要重新组织<code>from</code>后面<code>join</code>关联内容的顺序，SQLAlchemy提供了<code>select_from</code>来实现这个功能。通过<code>select_from</code>我们可以将整个<code>from</code>从句替换成SQLAlchemy支持的形式。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [41]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">order_id</span><span class="p">,</span> <span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span><span class="p">,</span> <span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">phone</span><span class="p">,</span>
            <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">,</span>
            <span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">extended_cost</span><span class="p">]</span>
<span class="n">cookiemon_orders</span> <span class="o">=</span> <span class="n">select</span><span class="p">(</span><span class="n">columns</span><span class="p">)</span>
<span class="n">cookiemon_orders</span> <span class="o">=</span> <span class="n">cookiemon_orders</span><span class="o">.</span><span class="n">select_from</span><span class="p">(</span><span class="n">orders</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">users</span><span class="p">)</span><span class="o">.</span><span class="n">join</span><span class="p">(</span>
                    <span class="n">line_items</span><span class="p">)</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">cookies</span><span class="p">))</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span> <span class="o">==</span>
                    <span class="s1">'cookiemon'</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">cookiemon_orders</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">result</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>(1, 'cookiemon', '111-111-1111', 'chocolate chip', 2, Decimal('1.00'))
(1, 'cookiemon', '111-111-1111', 'peanut butter', 12, Decimal('3.00'))
</pre>
</div>
</div>

<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stderr output_text">
<pre>d:\Miniconda3\lib\site-packages\sqlalchemy\sql\sqltypes.py:565: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.
  'storage.' % (dialect.name, dialect.driver))
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>上面的SQL语句是这样：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [42]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">cookiemon_orders</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>SELECT orders.order_id, users.username, users.phone, cookies.cookie_name, line_items.quantity, line_items.extended_cost 
FROM orders JOIN users ON users.user_id = orders.user_id JOIN line_items ON orders.order_id = line_items.order_id JOIN cookies ON cookies.cookie_id = line_items.cookie_id 
WHERE users.username = :username_1
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>统计所有用户各自的订单数量也常用，不只是当前的订单。可以通过<code>outerjoin()</code>方法实现，需要注意<code>join</code>的顺序，因为用<code>outerjoin()</code>方法生成的表会返回所有外键匹配结果。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [43]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span><span class="p">,</span> <span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">order_id</span><span class="p">)]</span>
<span class="n">all_orders</span> <span class="o">=</span> <span class="n">select</span><span class="p">(</span><span class="n">columns</span><span class="p">)</span>
<span class="n">all_orders</span> <span class="o">=</span> <span class="n">all_orders</span><span class="o">.</span><span class="n">select_from</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">outerjoin</span><span class="p">(</span><span class="n">orders</span><span class="p">))</span>
<span class="n">all_orders</span> <span class="o">=</span> <span class="n">all_orders</span><span class="o">.</span><span class="n">group_by</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span><span class="p">)</span> <span class="c1">#后面介绍分组</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">all_orders</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">result</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>('cakeeater', 1)
('cookiemon', 1)
('pieguy', 0)
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在，我们已经可以通过<code>join</code>实现关联查询了。但是，如果我们有一个像员工与老板关系表，用SQLAlchemy清楚的读取和理解内容需要用<code>alias</code>。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="Aliases">Aliases<a class="anchor-link" href="sqlalchemy-introduce.html#Aliases">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>用<code>join</code>的时候，通常要对一个表进行多次引用。在SQL里面，这是通过查询中的<code>aliases</code>实现的。例如，假设我们有下面的<code>schema</code>结构：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [44]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">employee_table</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span>
    <span class="s1">'employee'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
    <span class="n">Column</span><span class="p">(</span><span class="s1">'id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
    <span class="n">Column</span><span class="p">(</span><span class="s1">'manager_id'</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'employee.id'</span><span class="p">)),</span>
    <span class="n">Column</span><span class="p">(</span><span class="s1">'name'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">255</span><span class="p">)))</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在假如我们想选择<code>Fred</code>手下的所有员工。在SQL里面，我们会这么做：</p>
<div class="highlight"><pre><span></span><span class="k">SELECT</span> <span class="n">employee</span><span class="p">.</span><span class="n">name</span>
<span class="k">FROM</span> <span class="n">employee</span><span class="p">,</span> <span class="n">employee</span> <span class="k">AS</span> <span class="n">manager</span>
<span class="k">WHERE</span> <span class="n">employee</span><span class="p">.</span><span class="n">manager_id</span> <span class="o">=</span> <span class="n">manager</span><span class="p">.</span><span class="n">id</span>
<span class="k">AND</span> <span class="n">manager</span><span class="p">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">'Fred'</span>
</pre></div>
<p>SQLAlchemy也允许用<code>alias()</code>方法实现：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [45]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">manager</span> <span class="o">=</span> <span class="n">employee_table</span><span class="o">.</span><span class="n">alias</span><span class="p">(</span><span class="s1">'mgr'</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [46]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">stmt</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">employee_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">name</span><span class="p">],</span>
             <span class="n">and_</span><span class="p">(</span><span class="n">employee_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="o">==</span><span class="n">manager</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">,</span>
                 <span class="n">manager</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">name</span><span class="o">==</span><span class="s1">'Fred'</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [47]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="n">stmt</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>SELECT employee.name 
FROM employee, employee AS mgr 
WHERE employee.id = mgr.id AND mgr.name = :name_1
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>SQLAlchemy也可以自动选择别名：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [48]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">manager</span> <span class="o">=</span> <span class="n">employee_table</span><span class="o">.</span><span class="n">alias</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [49]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">stmt</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">employee_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">name</span><span class="p">],</span>
             <span class="n">and_</span><span class="p">(</span><span class="n">employee_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="o">==</span><span class="n">manager</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">id</span><span class="p">,</span>
                 <span class="n">manager</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">name</span><span class="o">==</span><span class="s1">'Fred'</span><span class="p">))</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [50]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="n">stmt</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>SELECT employee.name 
FROM employee, employee AS employee_1 
WHERE employee.id = employee_1.id AND employee_1.name = :name_1
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>数据分组<code>group_by</code>也是很有用的，下面我们来看看。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="Grouping">Grouping<a class="anchor-link" href="sqlalchemy-introduce.html#Grouping">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>SQLAlchemy可以对一个或多个列进行数据分组，然后统计各组的计数项（<code>count</code>），总和（<code>sum</code>）和其他统计参数，与SQL类似。下面我们看看每个客户的订单数：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [51]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span><span class="p">,</span> <span class="n">func</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">order_id</span><span class="p">)]</span>
<span class="n">all_orders</span> <span class="o">=</span> <span class="n">select</span><span class="p">(</span><span class="n">columns</span><span class="p">)</span>
<span class="n">all_orders</span> <span class="o">=</span> <span class="n">all_orders</span><span class="o">.</span><span class="n">select_from</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">outerjoin</span><span class="p">(</span><span class="n">orders</span><span class="p">))</span>
<span class="n">all_orders</span> <span class="o">=</span> <span class="n">all_orders</span><span class="o">.</span><span class="n">group_by</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">all_orders</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">result</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>('cakeeater', 1)
('cookiemon', 1)
('pieguy', 0)
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>前面的<code>join</code>的例子中我们已经用过，这里再看看<code>group_by</code>的用法。</p>
<h4 id="Chaining">Chaining<a class="anchor-link" href="sqlalchemy-introduce.html#Chaining">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>前面我们已经用过链式表达式，只是那时没有明说。进行数据查询时链式表达式能够清楚地显示查询的逻辑。因此，如果我们想用一个函数获取订单数据，可以如例3-28所示。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [52]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">get_orders_by_customer</span><span class="p">(</span><span class="n">cust_name</span><span class="p">):</span>
    <span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">order_id</span><span class="p">,</span> <span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span><span class="p">,</span> <span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">phone</span><span class="p">,</span>
                <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">,</span> 
                <span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">extended_cost</span><span class="p">]</span>
    <span class="n">cust_orders</span> <span class="o">=</span> <span class="n">select</span><span class="p">(</span><span class="n">columns</span><span class="p">)</span>
    <span class="n">cust_orders</span> <span class="o">=</span> <span class="n">cust_orders</span><span class="o">.</span><span class="n">select_from</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">orders</span><span class="p">)</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">line_items</span><span class="p">)</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">cookies</span><span class="p">))</span>
    <span class="n">cust_orders</span> <span class="o">=</span> <span class="n">cust_orders</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span> <span class="o">==</span> <span class="n">cust_name</span><span class="p">)</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">cust_orders</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">result</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [53]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">get_orders_by_customer</span><span class="p">(</span><span class="s1">'cakeeater'</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[53]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[(2, 'cakeeater', '222-222-2222', 'chocolate chip', 24, Decimal('12.00')),
 (2, 'cakeeater', '222-222-2222', 'oatmeal raisin', 6, Decimal('6.00'))]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>如果我们只想显示已发货或未发货的订单，怎么办？我们可以再写函数来支持其他选项，或者我们可以用链式查询来过滤。推荐后一种方法，尤其是处理复杂查询和制作报表时威力非常强大。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [54]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">get_orders_by_customer</span><span class="p">(</span><span class="n">cust_name</span><span class="p">,</span> <span class="n">shipped</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">details</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
    <span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">order_id</span><span class="p">,</span> <span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span><span class="p">,</span> <span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">phone</span><span class="p">]</span>
    <span class="n">joins</span> <span class="o">=</span> <span class="n">users</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">orders</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">details</span><span class="p">:</span>
        <span class="n">columns</span><span class="o">.</span><span class="n">extend</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">,</span>
                        <span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">extended_cost</span><span class="p">])</span>
        <span class="n">joins</span> <span class="o">=</span> <span class="n">joins</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">line_items</span><span class="p">)</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">cookies</span><span class="p">)</span>
    <span class="n">cust_orders</span> <span class="o">=</span> <span class="n">select</span><span class="p">(</span><span class="n">columns</span><span class="p">)</span>
    <span class="n">cust_orders</span> <span class="o">=</span> <span class="n">cust_orders</span><span class="o">.</span><span class="n">select_from</span><span class="p">(</span><span class="n">joins</span><span class="p">)</span>
    <span class="n">cust_orders</span> <span class="o">=</span> <span class="n">cust_orders</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span> <span class="o">==</span> <span class="n">cust_name</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">shipped</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">cust_orders</span> <span class="o">=</span> <span class="n">cust_orders</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">shipped</span> <span class="o">==</span> <span class="n">shipped</span><span class="p">)</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">cust_orders</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">result</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [55]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">get_orders_by_customer</span><span class="p">(</span><span class="s1">'cakeeater'</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[55]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[(2, 'cakeeater', '222-222-2222')]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [56]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">get_orders_by_customer</span><span class="p">(</span><span class="s1">'cakeeater'</span><span class="p">,</span> <span class="n">details</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[56]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[(2, 'cakeeater', '222-222-2222', 'chocolate chip', 24, Decimal('12.00')),
 (2, 'cakeeater', '222-222-2222', 'oatmeal raisin', 6, Decimal('6.00'))]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [57]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">get_orders_by_customer</span><span class="p">(</span><span class="s1">'cakeeater'</span><span class="p">,</span> <span class="n">shipped</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[57]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [58]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">get_orders_by_customer</span><span class="p">(</span><span class="s1">'cakeeater'</span><span class="p">,</span> <span class="n">shipped</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[58]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[(2, 'cakeeater', '222-222-2222')]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [59]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">get_orders_by_customer</span><span class="p">(</span><span class="s1">'cakeeater'</span><span class="p">,</span> <span class="n">shipped</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">details</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[59]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[(2, 'cakeeater', '222-222-2222', 'chocolate chip', 24, Decimal('12.00')),
 (2, 'cakeeater', '222-222-2222', 'oatmeal raisin', 6, Decimal('6.00'))]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>到此为止，我们已经用SQL表达式语言的例子演示了SQLAlchemy Core。其实，你也可以直接用标准的SQL语言来进行。</p>
<h4 id="Raw-Queries">Raw Queries<a class="anchor-link" href="sqlalchemy-introduce.html#Raw-Queries">¶</a>
</h4>
<p>在SQLAlchemy Core里面可以用原始的SQL语句进行操作，结果也是返回一个代理，后面的操作和SQLAlchemy Core的SQL表达式语法一样。除非必须，一般不推荐使用原始SQL，因为这么做存在安全隐患。下面我们简单演示一下。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [60]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">'select * from orders'</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>[(1, 1, 0), (2, 2, 0)]
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>有时候一些SQL小片段可以让语句表述更清晰。下面是用<code>text()</code>函数实现<code>where</code>的条件。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [61]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">text</span>
<span class="n">stmt</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">users</span><span class="p">])</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">text</span><span class="p">(</span><span class="s2">"username='cookiemon'"</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">stmt</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">())</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>[(1, None, 'cookiemon', 'mon@cookie.com', '111-111-1111', 'password', datetime.datetime(2015, 9, 1, 21, 37, 37, 531465), datetime.datetime(2015, 9, 1, 21, 37, 37, 531465))]
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>通过本章介绍的增删改查等操作，现在你应该已经理解SQLAlchemy Core的SQL表达式用法了，用自己的数据库试试吧。下面我们来介绍SQLAlchemy的异常处理，以及事务处理<code>transactions</code>分组的用法。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="Exceptions-and-Transactions">Exceptions and Transactions<a class="anchor-link" href="sqlalchemy-introduce.html#Exceptions-and-Transactions">¶</a>
</h2>
<p>前面做数据处理时，大部分工作我们都只用一行语句就搞定了，我们尽量避免做任何可能引起异常的事情，而本章我们会刻意搞点bug来演示异常处理方法。另外，我们还会介绍如何把对需要处理的任务分成单独的事务进行处理，保证每个事务都可以被适当地执行或正确地清理。</p>
<h3 id="Exceptions">Exceptions<a class="anchor-link" href="sqlalchemy-introduce.html#Exceptions">¶</a>
</h3>
<p>SQLAlchemy会产生许多不同类型的异常；不过这里只重点介绍一些常见的异常：<code>AttributeErrors</code>和<code>IntegrityErrors</code>。通过对常用异常处理方法的学习，你可以掌握其他异常的处理方法。</p>
<p>下面，请重新开一个Python shell或Notebook，然后用SQLAlchemy Core建立数据表。具体过程如例4-1所示。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [1]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">datetime</span>
<span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="p">(</span><span class="n">MetaData</span><span class="p">,</span> <span class="n">Table</span><span class="p">,</span> <span class="n">Column</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">,</span> <span class="n">String</span><span class="p">,</span>
                        <span class="n">DateTime</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">,</span> <span class="n">Boolean</span><span class="p">,</span> <span class="n">create_engine</span><span class="p">,</span>
                        <span class="n">CheckConstraint</span><span class="p">)</span>
<span class="n">metadata</span> <span class="o">=</span> <span class="n">MetaData</span><span class="p">()</span>
<span class="n">cookies</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'cookies'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_name'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">),</span> <span class="n">index</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_recipe_url'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">255</span><span class="p">)),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_sku'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">55</span><span class="p">)),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'quantity'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'unit_cost'</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">2</span><span class="p">)),</span>
                <span class="n">CheckConstraint</span><span class="p">(</span><span class="s1">'quantity &gt; 0'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">'quantity_positive'</span><span class="p">)</span>
                <span class="p">)</span>
<span class="n">users</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'users'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'user_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'username'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">15</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'email_address'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">255</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'phone'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">20</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'password'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">25</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'created_on'</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">(),</span> <span class="n">default</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'updated_on'</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">(),</span>
                     <span class="n">default</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">,</span> <span class="n">onupdate</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">)</span>
              <span class="p">)</span>
<span class="n">orders</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'orders'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
               <span class="n">Column</span><span class="p">(</span><span class="s1">'order_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
               <span class="n">Column</span><span class="p">(</span><span class="s1">'user_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'users.user_id'</span><span class="p">)),</span>
               <span class="n">Column</span><span class="p">(</span><span class="s1">'shipped'</span><span class="p">,</span> <span class="n">Boolean</span><span class="p">(),</span> <span class="n">default</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
               <span class="p">)</span>
<span class="n">line_items</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'line_items'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'line_items_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'order_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'orders.order_id'</span><span class="p">)),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'cookies.cookie_id'</span><span class="p">)),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'quantity'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'extended_cost'</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
                   <span class="p">)</span>
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s1">'sqlite:///:memory:'</span><span class="p">)</span>
<span class="n">metadata</span><span class="o">.</span><span class="n">create_all</span><span class="p">(</span><span class="n">engine</span><span class="p">)</span>
<span class="n">connection</span> <span class="o">=</span> <span class="n">engine</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [3]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">metadata</span><span class="o">.</span><span class="n">tables</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[3]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>dict_keys(['users', 'cookies', 'line_items', 'orders'])</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="AttributeError">AttributeError<a class="anchor-link" href="sqlalchemy-introduce.html#AttributeError">¶</a>
</h4>
<p><code>AttributeError</code>是指获取一个不存在的属性时产生的异常。经常是在连接<code>ResultProxy</code>里没有的一列时发生。在尝试获取一个对象不存在的属性时<code>AttributeError</code>也会发生。在普通的Python代码里也会发生。这里单独拿出来说是因为SQLAlchemy里非常容易出现这类异常，而其产生的根源却很容易忽略。为了演示这类异常，我们在<code>users</code>表里插入一列数据，然后我们查询没有<code>selsect</code>的一列来诱发异常。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [4]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">select</span><span class="p">,</span> <span class="n">insert</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">users</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span>
    <span class="n">username</span><span class="o">=</span><span class="s2">"cookiemon"</span><span class="p">,</span>
    <span class="n">email_address</span><span class="o">=</span><span class="s2">"mon@cookie.com"</span><span class="p">,</span>
    <span class="n">phone</span><span class="o">=</span><span class="s2">"111-111-1111"</span><span class="p">,</span>
    <span class="n">password</span><span class="o">=</span><span class="s2">"password"</span>
<span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [9]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span><span class="p">])</span>
<span class="n">results</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">for</span> <span class="n">result</span> <span class="ow">in</span> <span class="n">results</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">result</span><span class="o">.</span><span class="n">username</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">result</span><span class="o">.</span><span class="n">password</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>cookiemon
</pre>
</div>
</div>

<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_text output_error">
<pre>
<span class="ansi-red-intense-fg ansi-bold">---------------------------------------------------------------------------</span>
<span class="ansi-red-intense-fg ansi-bold">KeyError</span>                                  Traceback (most recent call last)
<span class="ansi-green-intense-fg ansi-bold">d:\programfiles\Miniconda3\lib\site-packages\sqlalchemy\engine\result.py</span> in <span class="ansi-cyan-fg">__getitem__</span><span class="ansi-blue-intense-fg ansi-bold">(self, key)</span>
<span class="ansi-green-fg">     69</span>             <span class="ansi-green-intense-fg ansi-bold">try</span><span class="ansi-yellow-intense-fg ansi-bold">:</span>
<span class="ansi-green-intense-fg ansi-bold">---&gt; 70</span><span class="ansi-yellow-intense-fg ansi-bold">                 </span>processor<span class="ansi-yellow-intense-fg ansi-bold">,</span> obj<span class="ansi-yellow-intense-fg ansi-bold">,</span> index <span class="ansi-yellow-intense-fg ansi-bold">=</span> self<span class="ansi-yellow-intense-fg ansi-bold">.</span>_keymap<span class="ansi-yellow-intense-fg ansi-bold">[</span>key<span class="ansi-yellow-intense-fg ansi-bold">]</span>
<span class="ansi-green-fg">     71</span>             <span class="ansi-green-intense-fg ansi-bold">except</span> KeyError<span class="ansi-yellow-intense-fg ansi-bold">:</span>

<span class="ansi-red-intense-fg ansi-bold">KeyError</span>: 'password'

During handling of the above exception, another exception occurred:

<span class="ansi-red-intense-fg ansi-bold">NoSuchColumnError</span>                         Traceback (most recent call last)
<span class="ansi-green-intense-fg ansi-bold">d:\programfiles\Miniconda3\lib\site-packages\sqlalchemy\engine\result.py</span> in <span class="ansi-cyan-fg">__getattr__</span><span class="ansi-blue-intense-fg ansi-bold">(self, name)</span>
<span class="ansi-green-fg">     95</span>             <span class="ansi-green-intense-fg ansi-bold">try</span><span class="ansi-yellow-intense-fg ansi-bold">:</span>
<span class="ansi-green-intense-fg ansi-bold">---&gt; 96</span><span class="ansi-yellow-intense-fg ansi-bold">                 </span><span class="ansi-green-intense-fg ansi-bold">return</span> self<span class="ansi-yellow-intense-fg ansi-bold">[</span>name<span class="ansi-yellow-intense-fg ansi-bold">]</span>
<span class="ansi-green-fg">     97</span>             <span class="ansi-green-intense-fg ansi-bold">except</span> KeyError <span class="ansi-green-intense-fg ansi-bold">as</span> e<span class="ansi-yellow-intense-fg ansi-bold">:</span>

<span class="ansi-green-intense-fg ansi-bold">d:\programfiles\Miniconda3\lib\site-packages\sqlalchemy\engine\result.py</span> in <span class="ansi-cyan-fg">__getitem__</span><span class="ansi-blue-intense-fg ansi-bold">(self, key)</span>
<span class="ansi-green-fg">     71</span>             <span class="ansi-green-intense-fg ansi-bold">except</span> KeyError<span class="ansi-yellow-intense-fg ansi-bold">:</span>
<span class="ansi-green-intense-fg ansi-bold">---&gt; 72</span><span class="ansi-yellow-intense-fg ansi-bold">                 </span>processor<span class="ansi-yellow-intense-fg ansi-bold">,</span> obj<span class="ansi-yellow-intense-fg ansi-bold">,</span> index <span class="ansi-yellow-intense-fg ansi-bold">=</span> self<span class="ansi-yellow-intense-fg ansi-bold">.</span>_parent<span class="ansi-yellow-intense-fg ansi-bold">.</span>_key_fallback<span class="ansi-yellow-intense-fg ansi-bold">(</span>key<span class="ansi-yellow-intense-fg ansi-bold">)</span>
<span class="ansi-green-fg">     73</span>             <span class="ansi-green-intense-fg ansi-bold">except</span> TypeError<span class="ansi-yellow-intense-fg ansi-bold">:</span>

<span class="ansi-green-intense-fg ansi-bold">d:\programfiles\Miniconda3\lib\site-packages\sqlalchemy\engine\result.py</span> in <span class="ansi-cyan-fg">_key_fallback</span><span class="ansi-blue-intense-fg ansi-bold">(self, key, raiseerr)</span>
<span class="ansi-green-fg">    405</span>                     <span class="ansi-blue-intense-fg ansi-bold">"Could not locate column in row for column '%s'"</span> <span class="ansi-yellow-intense-fg ansi-bold">%</span>
<span class="ansi-green-intense-fg ansi-bold">--&gt; 406</span><span class="ansi-yellow-intense-fg ansi-bold">                     expression._string_or_unprintable(key))
</span><span class="ansi-green-fg">    407</span>             <span class="ansi-green-intense-fg ansi-bold">else</span><span class="ansi-yellow-intense-fg ansi-bold">:</span>

<span class="ansi-red-intense-fg ansi-bold">NoSuchColumnError</span>: "Could not locate column in row for column 'password'"

During handling of the above exception, another exception occurred:

<span class="ansi-red-intense-fg ansi-bold">AttributeError</span>                            Traceback (most recent call last)
<span class="ansi-green-intense-fg ansi-bold">&lt;ipython-input-9-c4520631a10a&gt;</span> in <span class="ansi-cyan-fg">&lt;module&gt;</span><span class="ansi-blue-intense-fg ansi-bold">()</span>
<span class="ansi-green-fg">      3</span> <span class="ansi-green-intense-fg ansi-bold">for</span> result <span class="ansi-green-intense-fg ansi-bold">in</span> results<span class="ansi-yellow-intense-fg ansi-bold">:</span>
<span class="ansi-green-fg">      4</span>     print<span class="ansi-yellow-intense-fg ansi-bold">(</span>result<span class="ansi-yellow-intense-fg ansi-bold">.</span>username<span class="ansi-yellow-intense-fg ansi-bold">)</span>
<span class="ansi-green-intense-fg ansi-bold">----&gt; 5</span><span class="ansi-yellow-intense-fg ansi-bold">     </span>print<span class="ansi-yellow-intense-fg ansi-bold">(</span>result<span class="ansi-yellow-intense-fg ansi-bold">.</span>password<span class="ansi-yellow-intense-fg ansi-bold">)</span>

<span class="ansi-green-intense-fg ansi-bold">d:\programfiles\Miniconda3\lib\site-packages\sqlalchemy\engine\result.py</span> in <span class="ansi-cyan-fg">__getattr__</span><span class="ansi-blue-intense-fg ansi-bold">(self, name)</span>
<span class="ansi-green-fg">     96</span>                 <span class="ansi-green-intense-fg ansi-bold">return</span> self<span class="ansi-yellow-intense-fg ansi-bold">[</span>name<span class="ansi-yellow-intense-fg ansi-bold">]</span>
<span class="ansi-green-fg">     97</span>             <span class="ansi-green-intense-fg ansi-bold">except</span> KeyError <span class="ansi-green-intense-fg ansi-bold">as</span> e<span class="ansi-yellow-intense-fg ansi-bold">:</span>
<span class="ansi-green-intense-fg ansi-bold">---&gt; 98</span><span class="ansi-yellow-intense-fg ansi-bold">                 </span><span class="ansi-green-intense-fg ansi-bold">raise</span> AttributeError<span class="ansi-yellow-intense-fg ansi-bold">(</span>e<span class="ansi-yellow-intense-fg ansi-bold">.</span>args<span class="ansi-yellow-intense-fg ansi-bold">[</span><span class="ansi-cyan-intense-fg ansi-bold">0</span><span class="ansi-yellow-intense-fg ansi-bold">]</span><span class="ansi-yellow-intense-fg ansi-bold">)</span>
<span class="ansi-green-fg">     99</span> 
<span class="ansi-green-fg">    100</span> 

<span class="ansi-red-intense-fg ansi-bold">AttributeError</span>: Could not locate column in row for column 'password'</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>在例4-2中我们看到Python抛出了<code>AttributeError</code>并停止了程序，我们可以看到<code>AttributeError</code>是Python里常见的形式。首先显示错异常的类型，然后一个箭头会指明异常发生的位置，紧接着是异常发生源代码。最后一行会显示异常的具体内容，它会显示异常类型，以及为什么发生异常。这里出现异常的原因是ResultProxy里面没有<code>password</code>列，我们只查询了<code>username</code>列。这是在使用SQLAlchemy对象时出现的一个常见Python异常，还有一些SQLAlchemy自己特有的异常。下面就是其中一个：<code>IntegrityError</code>。</p>
<h4 id="IntegrityError">IntegrityError<a class="anchor-link" href="sqlalchemy-introduce.html#IntegrityError">¶</a>
</h4>
<p><code>IntegrityError</code>是另一个SQLAlchemy常见的异常，当我们做了不符合数据表或字段约束条件的事情时就会发生。当你请求的数据是唯一的，比如<code>users</code>表中的<code>username</code>,想创建两个同名用户时就会产生<code>IntegrityError</code>，演示程序如下所示。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [10]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">users</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">username</span><span class="p">])</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [12]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[12]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[('cookiemon',)]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [1]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">users</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span>
    <span class="n">username</span><span class="o">=</span><span class="s2">"cookiemon"</span><span class="p">,</span>
    <span class="n">email_address</span><span class="o">=</span><span class="s2">"damon@cookie.com"</span><span class="p">,</span>
    <span class="n">phone</span><span class="o">=</span><span class="s2">"111-111-1111"</span><span class="p">,</span>
    <span class="n">password</span><span class="o">=</span><span class="s2">"password"</span>
<span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>和前面的<code>AttributeError</code>类似。首先显示错异常的类型，然后一个箭头会指明异常发生的位置，紧接着是异常发生源代码。最后一行会显示异常的具体内容，它会显示异常类型，以及为什么发生异常。这里指明了发生的原因：</p>

<pre><code>UNIQUE constraint failed: users.username</code></pre>
<p>这就告诉我们在<code>users</code>表的<code>username</code>里面插入同名用户是不允许的。之后的内容是SQLAlchemy表达式转变成的SQL语句，我们在第三章里介绍过，还有我们计划插入却产生异常的数据。程序在这里停止。</p>
<p>当然会有很多种异常类型，这里介绍的两种是最常见的。SQLAlchemy里所有异常发生都会按照这两种方式产生。具体异常的内容请查看<a href="http://docs.sqlalchemy.org/en/latest/core/exceptions.html">SQLAlchemy文档</a>。</p>
<p>为了保证程序在发生异常时继续运行，我们需要实现异常处理方法。</p>
<h4 id="Handling-Errors">Handling Errors<a class="anchor-link" href="sqlalchemy-introduce.html#Handling-Errors">¶</a>
</h4>
<p>要防止异常中断程序，我们需要正确地处理异常。这与Python的异常处理方法一样，用<code>try/except</code>代码块实现。例如，我们可以用<code>try/except</code>代码块捕捉异常显示信息，然后让后面的程序继续运行。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [29]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy.exc</span> <span class="k">import</span> <span class="n">IntegrityError</span>

<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">users</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span>
    <span class="n">username</span><span class="o">=</span><span class="s2">"cookiemon"</span><span class="p">,</span>
    <span class="n">email_address</span><span class="o">=</span><span class="s2">"damon@cookie.com"</span><span class="p">,</span>
    <span class="n">phone</span><span class="o">=</span><span class="s2">"111-111-1111"</span><span class="p">,</span>
    <span class="n">password</span><span class="o">=</span><span class="s2">"password"</span>
<span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">)</span>
<span class="k">except</span> <span class="n">IntegrityError</span> <span class="k">as</span> <span class="n">error</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">error</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>(sqlite3.IntegrityError) UNIQUE constraint failed: users.username [SQL: 'INSERT INTO users (username, email_address, phone, password, created_on, updated_on) VALUES (?, ?, ?, ?, ?, ?)'] [parameters: ('cookiemon', 'damon@cookie.com', '111-111-1111', 'password', '2015-09-01 13:45:18.991258', '2015-09-01 13:45:18.992259')]
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>虽然和前面例子代码一样，但是因为有<code>try/except</code>处理<code>IntegrityError</code>异常，所有结果就是简单的异常信息。这个例子只是演示了异常打印功能，其实我们可以在异常处理中写任何Python代码。返回异常信息告诉用户刚刚的操作失败了是很有用的做法。异常处理完成后，程序还会继续运行。虽然这里只处理了<code>IntegrityError</code>，但对其他SQLAlchemy异常也适用。</p>
<blockquote>
<p><code>try/except</code>里面的代码越少越好。因为代码太多可能会出现你意料之外的异常，不符合你捕捉的目标。</p>
</blockquote>
<p>用传统的Python方法可以捕捉一行语句的异常，如果我们有多个数据库语句，彼此之间互相关联，这个方法可能就不适用了。这时，我们需要将那些语句封装成一个数据库事务，SQLAlchemy提供了一个简单的包装来建立对象之间的链接：transactions。</p>
<h3 id="Transactions">Transactions<a class="anchor-link" href="sqlalchemy-introduce.html#Transactions">¶</a>
</h3>
<p>我们不需要学习一堆数据库理论，可以把事务看成是一种确保多个数据库语句打包成一组运行成功或运行失败的处理方式。当启动一个事务的时候，我们记录数据库的状态，然后执行多条SQL语句。如果所有的SQL语句都能顺利执行，数据库就会不断的更新状态，忽略前面的状态，如下图所示。
<img src="transactions1.png" alt="">
但是，如果有一条语句运行失败了，整个数据库就要回退（rollback）到原来的状态，如下图所示。
<img src="transactions2.png" alt="">
举个我们可能会在之前建立的数据库里操作的例子。当客户买了我们的饼干之后，我们就需要把饼干邮寄给客户，同时更新库存量。但是，如果我们没有足够的饼干库存履行客户的订单需求，怎么办呢？我们就查检查库存，并且不邮寄订单。这就可以用事务解决。</p>
<p>我们再新建一个Python Shell或Notebook，还用第三章的表，只是为<code>quantity</code>字段增加一个<code>CheckConstraint</code>限制条件，即库存量不能小于0。然后我们创建用户<em>cookiemon</em>，并设置<em>chocolate chip</em>和<em>dark chocolate chip cookie</em>的库存量，其中<em>chocolate chip</em>库存量为12，<em>dark chocolate chip cookie</em>库存量为1，具体程序如下所示。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [1]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">datetime</span>
<span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="p">(</span><span class="n">MetaData</span><span class="p">,</span> <span class="n">Table</span><span class="p">,</span> <span class="n">Column</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">,</span> <span class="n">String</span><span class="p">,</span>
                        <span class="n">DateTime</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">,</span> <span class="n">Boolean</span><span class="p">,</span> <span class="n">create_engine</span><span class="p">,</span>
                        <span class="n">CheckConstraint</span><span class="p">)</span>

<span class="n">metadata</span> <span class="o">=</span> <span class="n">MetaData</span><span class="p">()</span>
<span class="n">cookies</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'cookies'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_name'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">50</span><span class="p">),</span> <span class="n">index</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_recipe_url'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">255</span><span class="p">)),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_sku'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">55</span><span class="p">)),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'quantity'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
                <span class="n">Column</span><span class="p">(</span><span class="s1">'unit_cost'</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">2</span><span class="p">)),</span>
                <span class="n">CheckConstraint</span><span class="p">(</span><span class="s1">'quantity &gt;= 0'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">'quantity_positive'</span><span class="p">)</span>
                <span class="p">)</span>
<span class="n">users</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'users'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'user_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'username'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">15</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'email_address'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">255</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'phone'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">20</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'password'</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="mi">25</span><span class="p">),</span> <span class="n">nullable</span><span class="o">=</span><span class="kc">False</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'created_on'</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">(),</span> <span class="n">default</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">),</span>
              <span class="n">Column</span><span class="p">(</span><span class="s1">'updated_on'</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">(),</span>
                     <span class="n">default</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">,</span> <span class="n">onupdate</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">)</span>
              <span class="p">)</span>
<span class="n">orders</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'orders'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
               <span class="n">Column</span><span class="p">(</span><span class="s1">'order_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
               <span class="n">Column</span><span class="p">(</span><span class="s1">'user_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'users.user_id'</span><span class="p">)),</span>
               <span class="n">Column</span><span class="p">(</span><span class="s1">'shipped'</span><span class="p">,</span> <span class="n">Boolean</span><span class="p">(),</span> <span class="n">default</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
               <span class="p">)</span>
<span class="n">line_items</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s1">'line_items'</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'line_items_id'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">(),</span> <span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'order_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'orders.order_id'</span><span class="p">)),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'cookie_id'</span><span class="p">,</span> <span class="n">ForeignKey</span><span class="p">(</span><span class="s1">'cookies.cookie_id'</span><span class="p">)),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'quantity'</span><span class="p">,</span> <span class="n">Integer</span><span class="p">()),</span>
                   <span class="n">Column</span><span class="p">(</span><span class="s1">'extended_cost'</span><span class="p">,</span> <span class="n">Numeric</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
                   <span class="p">)</span>
<span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s1">'sqlite:///:memory:'</span><span class="p">)</span>
<span class="n">metadata</span><span class="o">.</span><span class="n">create_all</span><span class="p">(</span><span class="n">engine</span><span class="p">)</span>
<span class="n">connection</span> <span class="o">=</span> <span class="n">engine</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>

<span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="k">import</span> <span class="n">select</span><span class="p">,</span> <span class="n">insert</span><span class="p">,</span> <span class="n">update</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">users</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span>
    <span class="n">username</span><span class="o">=</span><span class="s2">"cookiemon"</span><span class="p">,</span>
    <span class="n">email_address</span><span class="o">=</span><span class="s2">"mon@cookie.com"</span><span class="p">,</span>
    <span class="n">phone</span><span class="o">=</span><span class="s2">"111-111-1111"</span><span class="p">,</span>
    <span class="n">password</span><span class="o">=</span><span class="s2">"password"</span>
<span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">)</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">cookies</span><span class="o">.</span><span class="n">insert</span><span class="p">()</span>
<span class="n">inventory_list</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s1">'cookie_name'</span><span class="p">:</span> <span class="s1">'chocolate chip'</span><span class="p">,</span>
        <span class="s1">'cookie_recipe_url'</span><span class="p">:</span> <span class="s1">'http://some.aweso.me/cookie/recipe.html'</span><span class="p">,</span>
        <span class="s1">'cookie_sku'</span><span class="p">:</span> <span class="s1">'CC01'</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="s1">'12'</span><span class="p">,</span>
        <span class="s1">'unit_cost'</span><span class="p">:</span> <span class="s1">'0.50'</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">'cookie_name'</span><span class="p">:</span> <span class="s1">'dark chocolate chip'</span><span class="p">,</span>
        <span class="s1">'cookie_recipe_url'</span><span class="p">:</span> <span class="s1">'http://some.aweso.me/cookie/recipe_dark.html'</span><span class="p">,</span>
        <span class="s1">'cookie_sku'</span><span class="p">:</span> <span class="s1">'CC02'</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="s1">'1'</span><span class="p">,</span>
        <span class="s1">'unit_cost'</span><span class="p">:</span> <span class="s1">'0.75'</span>
    <span class="p">}</span>
<span class="p">]</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">,</span> <span class="n">inventory_list</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [2]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
<span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[2]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[('chocolate chip', 12), ('dark chocolate chip', 1)]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在，我们再定义两个<em>cookiemon</em>的订单，第一条订单是9块<em>chocolate chip</em>，第二条订单是4块<em>chocolate chip</em>和1块<em>dark chocolate chip cookie</em>。我们用插入语句来实现，具体如下所示。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [3]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">orders</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">user_id</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">order_id</span><span class="o">=</span><span class="s1">'1'</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">)</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">line_items</span><span class="p">)</span>
<span class="n">order_items</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s1">'order_id'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
        <span class="s1">'cookie_id'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span>
        <span class="s1">'extended_cost'</span><span class="p">:</span> <span class="mf">4.50</span>
    <span class="p">}</span>
<span class="p">]</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">,</span> <span class="n">order_items</span><span class="p">)</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">orders</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">user_id</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">order_id</span><span class="o">=</span><span class="s1">'2'</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">)</span>
<span class="n">ins</span> <span class="o">=</span> <span class="n">insert</span><span class="p">(</span><span class="n">line_items</span><span class="p">)</span>
<span class="n">order_items</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s1">'order_id'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span>
        <span class="s1">'cookie_id'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
        <span class="s1">'extended_cost'</span><span class="p">:</span> <span class="mf">0.75</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">'order_id'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span>
        <span class="s1">'cookie_id'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
        <span class="s1">'quantity'</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span>
        <span class="s1">'extended_cost'</span><span class="p">:</span> <span class="mf">2.00</span>
    <span class="p">}</span>
<span class="p">]</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">ins</span><span class="p">,</span> <span class="n">order_items</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这样我们就有了演示事务的订单数据了，现在我们需要定义一个函数<code>ship_it</code>。这个函数接受一个<code>order_id</code>，然后从库存中去掉对应的购买量，并把订单标记成已发货，<code>shipped=True</code>，如下所示。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [4]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sqlalchemy.exc</span> <span class="k">import</span> <span class="n">IntegrityError</span>
<span class="k">def</span> <span class="nf">ship_it</span><span class="p">(</span><span class="n">order_id</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_id</span><span class="p">,</span> <span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">order_id</span> <span class="o">==</span> <span class="n">order_id</span><span class="p">)</span>
        <span class="n">cookies_to_ship</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">cookie</span> <span class="ow">in</span> <span class="n">cookies_to_ship</span><span class="p">:</span>
            <span class="n">u</span> <span class="o">=</span> <span class="n">update</span><span class="p">(</span><span class="n">cookies</span><span class="p">)</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_id</span> <span class="o">==</span> <span class="n">cookie</span><span class="o">.</span><span class="n">cookie_id</span><span class="p">)</span>
            <span class="n">u</span> <span class="o">=</span> <span class="n">u</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">quantity</span><span class="o">=</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span> <span class="o">-</span> <span class="n">cookie</span><span class="o">.</span><span class="n">quantity</span><span class="p">)</span>
            <span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
        <span class="n">u</span> <span class="o">=</span> <span class="n">update</span><span class="p">(</span><span class="n">orders</span><span class="p">)</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">order_id</span> <span class="o">==</span> <span class="n">order_id</span><span class="p">)</span>
        <span class="n">u</span> <span class="o">=</span> <span class="n">u</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">shipped</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">"Shipped order ID: </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">order_id</span><span class="p">))</span>
    <span class="k">except</span> <span class="n">IntegrityError</span> <span class="k">as</span> <span class="n">error</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="n">error</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>当一条订单发货之后，函数<code>ship_it</code>就会执行动作。让我们对第一条订单执行函数<code>ship_it</code>，然后看看<code>cookies</code>表是否更新了库存。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [5]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">ship_it</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Shipped order ID: 1
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [6]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
<span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[6]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[('chocolate chip', 3), ('dark chocolate chip', 1)]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>运行正常。但是现在的库存量不能满足第二条订单；但是，在工作节奏很快的仓库中，这些订单应该可以同时处理。现在我们再用函数<code>ship_it</code>处理一下第二条订单。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [7]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">ship_it</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>(sqlite3.IntegrityError) CHECK constraint failed: quantity_positive [SQL: 'UPDATE cookies SET quantity=(cookies.quantity - ?) WHERE cookies.cookie_id = ?'] [parameters: (4, 1)]
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [8]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
<span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[8]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[('chocolate chip', 3), ('dark chocolate chip', 0)]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>程序中库存量先扣减1块<em>dark chocolate chip cookie</em>，可以正常执行，再扣减4块<em>chocolate chip</em>，因为没有足够的<code>chocolate chip</code>库存导致了<code>IntegrityError</code>异常。但是<code>dark chocolate chip</code>的库存扣减了，这不是我们想看到的。我们这里想要发生整个订单，不允许单独让一部分先发货。用前面介绍的异常处理方法可以解决这个问题，但是，事务提供了更好的处理方式。</p>
<p>事务通过<code>connection</code>对象的<code>begin()</code>方法启动。这样我们就获得一个事务，可以处理后面所有的语句。如果这些语句都成功执行，我们就可以用<code>commit()</code>方法对数据库进行状态确认。如果不完全成功，我们就用<code>rollback()</code>方法让数据库回退到原始状态。下面让我们用事务把函数<code>ship_it</code>改一下。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [9]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">ship_it</span><span class="p">(</span><span class="n">order_id</span><span class="p">):</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_id</span><span class="p">,</span> <span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">line_items</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">order_id</span> <span class="o">==</span> <span class="n">order_id</span><span class="p">)</span>
    <span class="n">transaction</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">begin</span><span class="p">()</span>
    <span class="n">cookies_to_ship</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">cookie</span> <span class="ow">in</span> <span class="n">cookies_to_ship</span><span class="p">:</span>
            <span class="n">u</span> <span class="o">=</span> <span class="n">update</span><span class="p">(</span><span class="n">cookies</span><span class="p">)</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_id</span> <span class="o">==</span> <span class="n">cookie</span><span class="o">.</span><span class="n">cookie_id</span><span class="p">)</span>
            <span class="n">u</span> <span class="o">=</span> <span class="n">u</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">quantity</span><span class="o">=</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="o">-</span><span class="n">cookie</span><span class="o">.</span><span class="n">quantity</span><span class="p">)</span>
            <span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
        <span class="n">u</span> <span class="o">=</span> <span class="n">update</span><span class="p">(</span><span class="n">orders</span><span class="p">)</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">orders</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">order_id</span> <span class="o">==</span> <span class="n">order_id</span><span class="p">)</span>
        <span class="n">u</span> <span class="o">=</span> <span class="n">u</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">shipped</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">"Shipped order ID: </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">order_id</span><span class="p">))</span>
        <span class="n">transaction</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
    <span class="k">except</span> <span class="n">IntegrityError</span> <span class="k">as</span> <span class="n">error</span><span class="p">:</span>
        <span class="n">transaction</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
        <span class="nb">print</span><span class="p">(</span><span class="n">error</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在我们把<code>dark chocolate chip</code>的库存重新补成1。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [10]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">u</span> <span class="o">=</span> <span class="n">update</span><span class="p">(</span><span class="n">cookies</span><span class="p">)</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span> <span class="o">==</span> <span class="s2">"dark chocolate chip"</span><span class="p">)</span>
<span class="n">u</span> <span class="o">=</span> <span class="n">u</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">quantity</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [11]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
<span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[11]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[('chocolate chip', 3), ('dark chocolate chip', 1)]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>再用新的函数<code>ship_it</code>对第二条订单进行处理。程序不会因为异常而停止，只会打印异常信息。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [13]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">ship_it</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>(sqlite3.IntegrityError) CHECK constraint failed: quantity_positive [SQL: 'UPDATE cookies SET quantity=(cookies.quantity - ?) WHERE cookies.cookie_id = ?'] [parameters: (4, 1)]
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>再用库存查看语句看看库存的状态，回退到第二条订单处理之前的状态了。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [14]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">select</span><span class="p">([</span><span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">cookie_name</span><span class="p">,</span> <span class="n">cookies</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">quantity</span><span class="p">])</span>
<span class="n">connection</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">
<div class="prompt output_prompt">Out[14]:</div>


<div class="output_text output_subarea output_execute_result">
<pre>[('chocolate chip', 3), ('dark chocolate chip', 1)]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这就是事务的作用，短短几行代码就可以让数据库回退到异常发生之前的状态，非常给力吧。</p>
<p>本章我们介绍了单行语句和成组的多行语句的异常处理方法。对单行语句可以通过<code>try/except</code>来防止程序因为出现异常而中断。我们还介绍了事务的处理方法，保证应用在处理成组的多行语句时不发生中断。现在，我们还需要学习如何测试代码的方法，保证其行为符合我们的预期，让我们开始下一章吧。</p>

</div>
</div>
</div>
    </div>
  </div>

    </div>
    <aside class="postpromonav"><nav><ul itemprop="keywords" class="tags">
<li><a class="tag p-category" href="../categories/ipython.html" rel="tag">ipython</a></li>
            <li><a class="tag p-category" href="../categories/sql.html" rel="tag">sql</a></li>
        </ul>
<ul class="pager hidden-print">
<li class="previous">
                <a href="postgres-import-csv-cp936-error.html" rel="prev" title="Postgres Import CSV cp936 Error">Previous post</a>
            </li>
            <li class="next">
                <a href="slott-2015146-2015-12-13-report.html" rel="next" title="双色球2015146期(2015-12-13)数据分析报告">Next post</a>
            </li>
        </ul></nav></aside><script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script><script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        processEscapes: true
    },
    displayAlign: 'center', // Change this to 'center' to center equations.
    "HTML-CSS": {
        styles: {'.MathJax_Display': {"margin": 0}}
    }
});
</script></article>
</div>
        <!--End of body content-->

        <footer id="footer">
            Contents © 2017         <a href="mailto:muxuezi@gmail.com">Tao Junjie</a> - Powered by         <a href="https://getnikola.com" rel="nofollow">Nikola</a>         
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0">
<img alt="Creative Commons License BY-NC-SA" style="border-width:0; margin-bottom:12px;" src="http://i.creativecommons.org/l/by-nc-sa/4.0/80x15.png"></a>
            
        </footer>
</div>
</div>


            <script src="../assets/js/all-nocdn.js"></script><script>$('a.image-reference:not(.islink) img:not(.islink)').parent().colorbox({rel:"gal",maxWidth:"100%",maxHeight:"100%",scalePhotos:true});</script><!-- fancy dates --><script>
    moment.locale("en");
    fancydates(0, "YYYY-MM-DD HH:mm");
    </script><!-- end fancy dates --><script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-51330059-1', 'auto');
  ga('send', 'pageview');

</script>
</body>
</html>
